Block Scope

// ES5
var x = 12;

if( x< 15){
  var msg = 'Quantity is small';
}

console.log(msg); // Quantity is small

// ES6
let x = 12;

if(x< 15){
  let msg = 'Quantity is small';
}

console.log(msg); // ReferenceError: msg is not defined

Example

ES5

var arr = [];

for( var i =0; i < 10; i++){
  arr.push(function(){
    console.log(i);
  });
}

arr.forEach(function(fn){
  fn(); // (10) 10 // printed 10 times
});

ES6 (using let)

var arr = [];

for( let i =0; i < 10; i++){
  arr.push(function(){
    console.log(i);
  });
}

arr.forEach(function(fn){
  fn();
});

// output
0
1
2
3
4
5
6
7
8
9

Last updated