ES6 For Beginners : Using The Let keyword

In this post we will discuss what is the new let keyword in ES6. And how to use it. The let keyword is used to declare block level variables.

Before the let keyword we used var to declare variables but that has some issues. Take a look at the following code snippet

1

2

3

4

5

6

7

varname="john";

if(1==1){

varname="jane";

}

alert(name);

We have declare the name variable to be the string “john” then inside the if condition we are declaring another name variable with the string “jane”, finally when we alert we expect the value of name to be “john” but what we get is “jane”.

Even though we declared the second name variable inside the if condition it makes change to the global variable.

As shown the variable inside the if condition is declared with the let keyword. This means that the global variable is untouched and we can use the variable inside the braces ({}) without having to worry about it making changers to the global scope.

In the snippets only if condition is shown but let can be used with any block of code that uses blocks so it can be used with for loops,functions ,etc

Using let With for Loop

So for example with a for loop we can use the let keyword as follows

1

2

3

for(leti=0,i++,i<20){

//loop scope

}

Here instead of using var i=0 like we did up till now we use let i=0 this makes the variable i scoped to the for loop and does not pollute the global scope