ES6 introduced **let** and **const** to fix `var`'s problems: function-scoping, hoisting, and no block-scoping. Both are **block-scoped** and have a **Temporal Dead Zone** (TDZ). `const` prevents reassignment but not mutation of objects. Always prefer const, use let when needed, avoid var.
1Understanding let & const (ES6)
ES6 introduced let and const to fix var's problems: function-scoping, hoisting, and no block-scoping. Both are block-scoped and have a Temporal Dead Zone (TDZ). const prevents reassignment but not mutation of objects. Always prefer const, use let when needed, avoid var.
The rule of thumb: use const by default. Only switch to let when you know you need to reassign.
// Block scoping prevents leaking
{
let blockLet = 'inside';
const blockConst = 'also inside';
console.log(blockLet); // inside
}
// console.log(blockLet); // ReferenceError!
// var leaks
{
var leaked = 'I escape blocks!';
}
console.log(leaked); // 'I escape blocks!'2Practical Example
Here is a real-world application of let & const (ES6) showing how it is used in production JavaScript code.
// TDZ: Temporal Dead Zone
try {
console.log(myLet); // ReferenceError - in TDZ!
} catch(e) {
console.log(e.message);
}
let myLet = 'now defined';3Best Practices
Follow these guidelines when working with let & const (ES6):
1. Default to const, use let only for reassignment
2. Never use var in modern code
3. Understand the TDZ to avoid ReferenceErrors
Tip: The rule of thumb: use const by default. Only switch to let when you know you need to reassign.
// Block scoping prevents leaking
{
let blockLet = 'inside';
const blockConst = 'also inside';
console.log(blockLet); // inside
}
// console.log(blockLet); // ReferenceError!
// var leaks
{
var leaked = 'I escape blocks!';
}
console.log(leaked); // 'I escape blocks!'