Why Let instead Var

Let is another type of variable declaration, one of the difference I found useful is the block scoping because this limit the scope of the variable and help us with confusions or errors of the scoping on javascript, but there are another and useful difference too.


let start = "This is my first variable";

Variables belong to the block where are declared, inside a function, inside a if/for/try-catch block only.


function testColor(color:string){
 let myColor="pink";

 if(color == myColor){
   let result = "You like my color";// creating "result" variable inside if block only will be available inside this if block.
   return result;
 }

return result; // Error: result does not exist.
}

Block scoping
-the scope of result variable is limited to if statement’s block.
-the scope of myColor variable is limited to testColor function.

Variables needs to be declared before use it.


function myColor (){

return color;

}

myColor();// Error: color variable does not exist,.

let color = "pink";

Duplicated variables are not valid.


let color = "pink";

let color = "blue"; // Error: Can not be declared color again in the same scope.

 

 

Leave a comment

Create a website or blog at WordPress.com

Up ↑