Block scope variable – ECMAScript 6
May 3, 2015
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.