Lesson 7 +10 XP

JavaScript Let

JavaScript Let

The let keyword was added in ES6 (2015) as a better way to declare variables.

Block scoped

Variables declared with let are block scoped. They only exist inside the block ({ }) where they are defined:

{
  let x = 2;
}
console.log(x); // Error: x is not defined

No redeclaring

You cannot redeclare a let variable in the same scope:

let x = 1;
let x = 2; // Error!

Redeclaring in different scopes is fine

let x = 1;
{
  let x = 2; // different scope, OK
}

let in loops

let is perfect for loop counters because each iteration gets its own copy:

for (let i = 0; i < 3; i++) {
  console.log(i);
}

Why prefer let?

let prevents the accidental global variables and redeclaration bugs that var allowed.

TL;DR

  • let is block scoped.
  • You cannot redeclare a let variable in the same scope.
  • Each loop iteration gets its own copy of a let counter.
  • let fixes common bugs caused by var.