Follow me if you want to grow your full-stack JavaScript skills with my screencasts and courses.

ES6 - the let keyword

Resources

Google traceur transpiler: https://github.com/google/traceur-compiler

Good and up to date ES6 code samples: https://github.com/lukehoban/es6features

A compatibility table for ES6 features: http://kangax.github.io/es5-compat-table/es6/

A special thanks for sharing previous episodes!

An example of a variable clash

app.js
  

    var x = 999;

    for(var i =0; i<10; i++){
        var x = i * 2;
        console.log(x);
    }

    console.log('this is the final value of x', x);
  

Running the above code produces the wrong results, it changes the outer x from 999 to 18 after the loop, as you can see from this output:

output
  
0
2
4
6
8
10
12
14
16
18
this is the final value of x 18

  

Fix it with let

app.js
  

    var x = 999;

    for(var i =0; i<10; i++){
        let x = i * 2;
        console.log(x);
    }

    console.log('this is the final value of x', x);
  

Simply introducing let in the inner scope leaves the outer x to be 999, this is the output:

output
  
0
2
4
6
8
10
12
14
16
18
this is the final value of x 999

  

Wrap up

Let allows us to focus on more interesting problems, instead of having a fear that a variable has been used before and that we might be overwriting it.