ES6: The let keyword

I’m starting a series on ES6. I will be giving readers a look into some of the more popular and useful features.

The first new feature we’ll dive into is the let keyword.

Block Scope

The let keyword is used to define a variable in a similar manner as the var keyword. A big difference though, is that the var statement is defined on an entire function or global scope. The let keyword is scoped to the block, statement or expression scope used.

Another key difference is that the var keyword hoists variables while the let keyword does not. What that means, simply, is that if you try to use a let declared variable before the declaration you’ll get a reference error. It doesn’t exist yet.

For Loop

When it comes to for loops the new let keyword has an important distinction.

If you declare let inside of a for loop instead of using the var declaration each iteration of the for loop gets a unique variable. If you declare via the var variable then that variable gets hoisted and only declared once. So any modification to the var declared variable needs to be carefully considered.

Checkout the example below:

In this example, if you come from synchronous languages like I do, you would probably take a quick look at the first loop and assume the console.log would return these four values: 1, 2, 3, 4. But, like I mentioned earlier that var declaration is only declared once at a function level. So, the actual value of i is 5 before the first setTimeout function executes and you get 5 printed out each time.

The let declaration is unique to each iteration so you get back the results you might have expected: 1, 2, 3, 4. You’ll also notice I assigned 9 to i at the very top of the IIFE just to show that i was indeed hoisted and no Reference Exception was thrown.