var vs let

You may think that let is the new var with an exception that let does not allow hoisting.

This was my original understanding also last year.

However, I learned recently that there are other differences as well.

Take a look at this iteration.


for (var i = 1; i < 6; ++i) {
  setTimeout(function () {
    console.log(i); // outputs '6' 5 times
  }, 100);  
}

for (let i = 1; i < 6; ++i) {
  setTimeout(function () {
    console.log(i); // outputs 1, 2, 3, 4, 5 
  }, 100);  
}

As you can see, let binds to each iteration. So let is not just a new block scope but actually behaves differently than var.

If you are used to variable hoisting, using let may feel restrictive. However, in ES6, declaration hoisting can be done with const.

//Declaration:
function foo() {}
//Expression:
const foo = function () {};
//Expression with arrow:
const foo = () => {};

Why this change? var often causes confusion when you try to maintain a large code.