let and const
let and const
Section titled “let and const”What it is
Section titled “What it is”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.
Before this feature
Section titled “Before this feature”Only var was available, with function scope and hoisting issues:
// var has function scope, not block scopefunction example() { if (true) { var x = 10; } console.log(x); // 10 - accessible outside block!}
// Hoisting causes confusionconsole.log(y); // undefined (not an error!)var y = 5;
// Loop variable leaksfor (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Prints: 3, 3, 3After this feature
Section titled “After this feature”let and const provide block scope and temporal dead zone:
// let has block scopefunction example() { if (true) { let x = 10; } console.log(x); // ReferenceError: x is not defined}
// No hoisting (temporal dead zone)console.log(y); // ReferenceErrorlet y = 5;
// Loop variable is scoped to iterationfor (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Prints: 0, 1, 2
// const prevents reassignmentconst 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 propertiesuser.age = 25; // OK - adding propertiesuser = {}; // TypeError - can't reassignWhy this is better
Section titled “Why this is better”- Block scope: Variables only exist in their block
- No hoisting: Can’t use before declaration (temporal dead zone)
- Immutability:
constprevents reassignment - Loop safety: Each iteration gets its own variable
- Clearer intent:
constsignals non-reassignment
Key notes / edge cases
Section titled “Key notes / edge cases”constprevents reassignment, not mutation of objects/arrays- Both create temporal dead zone (can’t access before declaration)
letallows reassignment,constdoesn’t- Always prefer
const, useletonly when reassignment needed - Never use
varin modern JavaScript
// Temporal dead zone{ // TDZ starts console.log(x); // ReferenceError let x = 5; // TDZ ends}
// const with arraysconst arr = [1, 2, 3];arr.push(4); // OKarr[0] = 10; // OKarr = []; // TypeError
// const requires initializationconst x; // SyntaxErrorconst y = 5; // OKQuick practice
Section titled “Quick practice”-
What’s the difference between
letandconst?Answer
`let` allows reassignment; `const` doesn't. Both are block-scoped. -
Can you modify properties of a
constobject?Answer
Yes. `const` prevents reassignment of the variable, not mutation of the object's properties. -
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.