ES2015 – Using let

The first new feature we will look at is a new keyword in JavaScript, the let keyword. let allows us to define variables. We always had the ability to define variables in JavaScript and we have done this with the var keyword. However, the var keyword has some limitations when it comes to scope. The scope of a variable defines the area of a program where the variable is legal to use. But with var there are only two types of scope for a variable. There is a global scope which is where I would place a variable if I define the variable with var outside of any function and then there is function scope for variables defined inside a function and there is no block scope. And this is the source of confusion and occasionally bugs particularly if you come from a background of using one of the other many languages that use curly braces to define blocks of code.

var doWork = function(flag){
if(flag){
var x = 3;
}
return x;
};

In the above code snippet, it looks like I have a variable defined as x that lives inside of the if statement but in reality because var can only give me function scoped variables, x is available throughout that function and the return keyword is going to work perfectly well because there is going to be a variable named x inside of doWork and that is the problem that  let will solve.

var doWork = function(flag){
if(flag){
let x = 3;
}
return x;
};

The let keyword will give us true block scoping. The above code snippet will generate an error if there is no other x variable defined in the outer scope. There will be an error because x is only available to use inside of the if block.

Moving forward when we are all programming with this new version of JavaScript it will be a good idea to use the let keyword instead of the var keyword to avoid this implicit variable hoisting and some of the confusing behavior that it can produce. The block scoping also works for a for statement. In the future then, let will be the replacement for var because it will allow us to declare variables where we need them, it will avoid hoisting and it will give us true block scoping which is what most developers expect.