Skip to content

let and const

let and const are block-scoped variable declarations introduced in ES6 (2015). They replace the problematic var keyword, providing better scoping and preventing accidental global variables.

Only var was available, with function scope and hoisting issues:

// var has function scope, not block scope
function example() {
if (true) {
var x = 10;
}
console.log(x); // 10 - accessible outside block!
}
// Hoisting causes confusion
console.log(y); // undefined (not an error!)
var y = 5;
// Loop variable leaks
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3

let and const provide block scope and temporal dead zone:

// let has block scope
function example() {
if (true) {
let x = 10;
}
console.log(x); // ReferenceError: x is not defined
}
// No hoisting (temporal dead zone)
console.log(y); // ReferenceError
let y = 5;
// Loop variable is scoped to iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2
// const prevents reassignment
const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable
// const with objects (properties can change)
const user = { name: "Alice" };
user.name = "Bob"; // OK - mutating properties
user.age = 25; // OK - adding properties
user = {}; // TypeError - can't reassign
  • Block scope: Variables only exist in their block
  • No hoisting: Can’t use before declaration (temporal dead zone)
  • Immutability: const prevents reassignment
  • Loop safety: Each iteration gets its own variable
  • Clearer intent: const signals non-reassignment
  • const prevents reassignment, not mutation of objects/arrays
  • Both create temporal dead zone (can’t access before declaration)
  • let allows reassignment, const doesn’t
  • Always prefer const, use let only when reassignment needed
  • Never use var in modern JavaScript
// Temporal dead zone
{
// TDZ starts
console.log(x); // ReferenceError
let x = 5; // TDZ ends
}
// const with arrays
const arr = [1, 2, 3];
arr.push(4); // OK
arr[0] = 10; // OK
arr = []; // TypeError
// const requires initialization
const x; // SyntaxError
const y = 5; // OK
  1. What’s the difference between let and const?

    Answer`let` allows reassignment; `const` doesn't. Both are block-scoped.
  2. Can you modify properties of a const object?

    AnswerYes. `const` prevents reassignment of the variable, not mutation of the object's properties.
  3. Why does this print 3 three times? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }

    Answer`var` has function scope, so all callbacks share the same `i` variable. By the time they execute, `i` is 3. Use `let` instead.