JavaScript ES6: let and scope

Thu May 18 2017

One of the things about ES6 that some people might find a little different is the addition of "let" and the changes to the way scoping is handled. In the code above, I have commented on some of the changes but lets take a closer look.

As you can see in the top two examples, the global scope and the scoping within a function is basically the same. Where the difference emerges is in the 3rd example. When you use let within the context of a for loop, the variable "corgi" is not available outside of the loop context. To me and my logic, I prefer this.

In the 4th example, you can see that the variable wolf is available outside the context of the loop. Tomato vs mater.

Overall, I prefer the greater control let/ES6 gives us over the scoping of our code. Now lets take a quick look at Redeclaration in ES6.

'use strict';
let jacob = 'jake';
let jacob = 'jack'; // SyntaxError: Identifier 'jacob' has already been declared

'use strict';
var jacob = 'jake';
var jacob = 'jack'; // all good, `jacob` is replaced.

ALL HAIL ES SIX


Edit