Difference between var, let & const in JS
In JavaScript, variable declaration is not merely syntactic—it defines scope boundaries, mutability guarantees, and runtime behavior under hoisting. The distinction between var, let, and const is therefore foundational to writing predictable code.
1. var — Function Scope, Legacy Semantics
var is function-scoped, not block-scoped. Its declaration is hoisted and initialized with undefined, making it accessible before its actual definition.
function example() {
console.log(x); // undefined (not error)
var x = 10;
}
This behavior leads to scope leakage:
if (true) {
var a = 5;
}
console.log(a); // 5 (escapes block)
Additionally, var permits re-declaration within the same scope, increasing the risk of unintended overrides.
var x = 10;
var x = 20; // valid, but unsafe
Conclusion: var reflects older design decisions and is unsuitable for modern, maintainable systems.
2. let — Block Scope with Controlled Mutability
let introduces block-level scoping, aligning variable visibility with logical code boundaries.
if (true) {
let a = 5;
}
console.log(a); // ReferenceError
Although let is hoisted, it resides in the Temporal Dead Zone (TDZ) until initialization, preventing premature access:
console.log(x); // ReferenceError
let x = 10;
Re-declaration within the same scope is disallowed, enforcing stricter discipline:
let x = 10;
// let x = 20; // SyntaxError
However, reassignment is permitted, making it suitable for evolving state.
3. const — Immutable Binding, Not Immutable Value
const also provides block scope and participates in the TDZ. It must be initialized at declaration and cannot be reassigned thereafter.
const x = 10;
// x = 20; // TypeError
Crucially, const enforces immutability of the binding, not the underlying value:
const obj = { name: "A" };
obj.name = "B"; // valid (mutation allowed)
// obj = {}; // invalid (reassignment)
Thus, const guarantees reference stability, not deep immutability.
4. Guideline