JavaScript let

The let keyword was introduced in ES6 (2015). let is block-scoped and fixes the main quirks of var.

let is Block-Scoped

A let variable only exists inside the block ({}) where it was declared. It does not leak into the outer scope.

Block Scope
if (true) {
    let x = 10;   // only lives inside this if block
    console.log(x);  // 10
}
// console.log(x);  // ReferenceError: x is not defined

let Cannot Be Re-declared

No Re-declaration
let name = "Alice";
// let name = "Bob"; // SyntaxError: already declared

name = "Bob";         // reassigning is fine
console.log(name);    // "Bob"

Temporal Dead Zone (TDZ)

let is hoisted but NOT initialised. Accessing it before declaration throws a ReferenceError. The period before declaration is called the Temporal Dead Zone.

Temporal Dead Zone
// console.log(value);  // ReferenceError: Cannot access before initialisation
let value = 42;
console.log(value);     // 42

let Fixes the Loop Bug

let in Loops
// Each iteration gets its OWN block-scoped variable
const fns = [];
for (let i = 0; i < 3; i++) {
    fns.push(() => i);
}
console.log(fns[0]());  // 0
console.log(fns[1]());  // 1
console.log(fns[2]());  // 2
Featurelet
ScopeBlock
Re-declareNot allowed
HoistedYes, but in TDZ — cannot use before declaration
ReassignYes
📝 Note: Use let when you know the value will change. For values that should not change, use const.
Exercise:
Can let be redeclared in the same scope?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.