Declaring with let

A let declaration is scope-based. It cannot be declared more than once per scope, and it does not hoist the variable. It simplifies the readability of the code, and it avoids unexpected errors. Declaring with let also doesn't set any values globally. Relying on let is the way to declare a variable when you expect the variable to be set more than once. In the following code, the variable a is defined three times. The code is legal, even with several declarations. The reason is that each declaration, with let, is defined in a different scope with curly braces. The first scope is the function scope. The second scope uses an unusual syntax, but it reflects how a while, if, or other scope feature works. The third scope is within an if statement:

function letFunction() {
let a: number = 1;
{ // Scope start
let a: number = 2;
} // Scope end
console.log(a); // 1

if(true){ // Scope start
let a: number = 3;
} // Scope end
console.log(a); // 1
}
letFunction()

Furthermore, TypeScript ensures that once a declaration is done, the type associated with the variable is immutable. This means that a variable defined as a number will be a number for the rest of the lifespan of the variable:

let a:number = 2;
a = "two"; // Doesn’t compile

Declaring a variable with let in a switch case can be tricky. The reason is the scoping is not by case but for the switch that hosts all the cases. However, it is possible to conceive a scope by summoning a curly bracket inside each case. The following code is valid even if two variables b are declared:

function switchFunction(num: number) {
let b: string = "functionb";

switch (num) {
case 1:
let b: string = "case 1";
break;
}
}

However, adding a subsequent case that also declares a variable b fails the compilation:

function switchFunction(num: number) {
let b: string = "functionb";

switch (num) {
case 1:
let b: string = "case 1";
break;
case 2:
let b: string = "case 2";
break;
}
}

The workaround for the default scope from the switch is to create an artificial scope for each case. The construction of the scope can be done by adding curly brackets, as shown in the following code:

function switchFunction(num: number) {
let b: string = "functionb";

switch (num) {
case 1: {
let b: string = "case 1";
break;
} // After break
case 2: {
let b: string = "case 2";
} // Before break
break;
}

}

let is one of the most-used declarations and should always be used instead of var when const is not a valid option.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.61.133