Block scope variable - ECMAScript 6

Since some of ECMAScript 6 features looks weird to old-fashioned JavaScripters, I’m going to write a series of blog posts to describe the main idea of some common ECMAScript 6 features.

In this posts I’d like to explain the usage of block scope variables. The keyword let enables you to create a block scope variable in ECMAScript 6:

let boo = 1; 

So, what’s the difference between var boo = 1; and let boo = 1;? Assume following example:

function sample() { if (true) { var boo = 1; } return boo; } console.log(sample()); //returns 1 

In the above old-fashioned code, boo variable is defined within the sample function scope so we have the value even outside of the if statement.

With let variable you can create a variable that is available within the if statement block:

function sample() { if (true) { let boo = 1; } return boo; //ReferenceError: boo is not defined } console.log(sample()); 

Awesome, isn’t it?

I will write more blog posts about ECMAScript 6 features soon.

 
45
Kudos
 
45
Kudos

Now read this

Using `object` as the keys of another `object` in JavaScript

Sometimes you need to use objects for the keys of a dictionary (let’s say, another object). Assume this code: var keys = [{a: 1}, {a: 2}, {a: 3}]; var dic = {}; //add a new key to the dictionary dic[keys[0]] = 'boo'; dic[keys[1]] =... Continue →