ES6 in Action: let and const

Original Source: https://www.sitepoint.com/es6-let-const/

In this tutorial, I’ll introduce let and const, two new keywords added to JavaScript with the arrival of ES6. They enhance JavaScript by providing a way to define block-scope variables and constants.

This article is one of many covering new features of JavaScript introduced with ES6, including Map and WeakMap, Set and WeakSet, new methods available for String, Number, and Array, and the new syntax available for functions.

let

Up to ES5, JavaScript had only two types of scope, function scope and global scope. This caused a lot of frustration and unexpected behaviors for developers coming from other languages such as C, C++ or Java. JavaScript lacked block scope, meaning that a variable is only accessible within the block in which it’s defined. A block is everything inside an opening and closing curly bracket. Let’s take a look at the following example:

function foo() {
var par = 1;
if (par >= 0) {
var bar = 2;
console.log(par); // prints 1
console.log(bar); // prints 2
}
console.log(par); // prints 1
console.log(bar); // prints 2
}
foo();

After running this code, you’ll see the following output in the console:

1
2
1
2

What most developers coming from the languages mentioned above would expect, is that outside the if block you can’t access the bar variable. For example, running the equivalent code in C results in the error ‘bar’ undeclared at line … which refers to the use of bar outside the if.

This situation changed in ES6 with the availability of block scope. The ECMA organization members knew that they could not change the behavior of the keyword var, as that would break backward compatibility. So they decided to introduce a new keyword called let. The latter can be used to define variables limiting their scope to the block in which they are declared. In addition, unlike var, variables declared using let aren’t hoisted. If you reference a variable in a block before the let declaration for that variable is encountered, this results in a ReferenceError. But what does this mean in practice? Is it only good for newbies? Not at all!

To explain you why you’ll love let, consider the following code taken from my article 5 More JavaScript Interview Exercises:

var nodes = document.getElementsByTagName(‘button’);
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener(‘click’, function() {
console.log(‘You clicked element #’ + i);
});
}

Here you can recognize a well-known issue that comes from variable declaration, their scope, and event handlers. If you don’t know what I’m talking about, go check the article I mentioned and than come back.

Thanks to ES6, we can easily solve this issue by declaring the i variable in the for loop using let:

var nodes = document.getElementsByTagName(‘button’);
for (let i = 0; i < nodes.length; i++) {
nodes[i].addEventListener(‘click’, function() {
console.log(‘You clicked element #’ + i);
});
}

The let statement is supported in Node and all modern browsers. There are, however, a couple of gotchas in Internet Explorer 11 which you can read about in the ES6 compatability table.

A live demo that shows the difference between var and let is shown below and is also available at JSBin:

ES6 in Action: let and const on jsbin.com

Continue reading %ES6 in Action: let and const%

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *