Lesson 4. Declaring variables with let

 

After reading lesson 4, you will

  • Understand how scope works with let and how it differs from var
  • Understand the difference between block scope and function scope
  • Understand how let variables are hoisted

In the history of JavaScript, variables have always been declared using the keyword var.[1] ES6 introduces two new ways to declare variables, with the let and const keywords.[2] Both of these work slightly differently than variables declared with var. There are two primary differences with let:

1Actually, in non-strict mode, it was possible to create a new variable while completely omitting the var declaration altogether. This, however, created a global, usually unbeknownst to the author, leading to some pretty fun bugs. This is why var is required in strict mode.

2Technically consts are not variables but constants.

  • let variables have different scoping rules.
  • let variables behave differently when hoisted.
Consider this

Consider the following two for statements. The only difference is that one is using an iterator declared with var and the other with let. But the resulted outcome is much different. What do you think will happen when each one runs?

for (var i = 0; i < 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, 1);
};
for (let n = 0; n < 5; n++) {
  setTimeout(function () {
    console.log(n);
  }, 1);
};

4.1. How scope works with let

4.2. How hoisting works with let

4.3. Should I use let instead of var from now on?

Summary