let vs const vs var
Modern JavaScript gives you three ways to declare variables. Each serves a different purpose. Getting this right means fewer bugs and cleaner code.
- const โ value cannot be reassigned. Use this by default.
- let โ can be reassigned. Use when you need to update the value.
- var โ old way. Avoid in modern code.
let vs const
let score = 10;
score = 20; // Works fine
const maxScore = 100;
maxScore = 200; // Error: Assignment to constant variable
Try it Yourself โ
const Does Not Mean Immutable
const person = { name: "Alice" };
person.name = "Bob"; // Works โ const prevents reassignment, not mutation
console.log(person);
// person = {}; // Error!
Try it Yourself โ
Block Scope vs Function Scope
if (true) {
var a = "visible everywhere";
let b = "only in this block";
}
console.log(a); // Works
console.log(b); // ReferenceError
Try it Yourself โ
Temporal Dead Zone (TDZ)
console.log(x); // undefined (var is hoisted)
var x = 5;
console.log(y); // ReferenceError: Cannot access before initialization
let y = 5;
Try it Yourself โ
let and const exist in a "temporal dead zone" from the start of the block until they're declared.