What is the real difference between var, let, and const in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

What is the real difference between var, let, and const in JavaScript?

message-square
0

The real differences between var, let, and const come down to scope (function-scoped vs. block-scoped), hoisting and the Temporal Dead Zone (TDZ) (undefined initialization vs. uninitialized TDZ throwing ReferenceError), redeclaration (allowed with var, forbidden in the same scope with let and const), and reassignment (const prevents reassigning the binding itself, not mutating objects/arrays it holds). In modern JavaScript, default to const, use let when the variable needs to be reassigned, and avoid var in new code.


1. Side-by-Side Comparison: var vs. let vs. const

Behavior var let const
Scope Function scope (or global) Block scope ({ ... }) Block scope ({ ... })
Redeclarable in same scope? Yes No (SyntaxError) No (SyntaxError)
Reassignable? Yes Yes No (TypeError)
Must initialize at declaration? No No Yes (SyntaxError if omitted)
Before declaration access undefined (hoisted & initialized) ReferenceError (Temporal Dead Zone) ReferenceError (Temporal Dead Zone)
Top-level global property (window) Attached to window in global script Not attached to window Not attached to window

2. Scoping, Hoisting (TDZ), and const Immutability in Practice

Understanding how block scope, the Temporal Dead Zone, and const object bindings behave prevents subtle bugs in loops, if/for blocks, and async callbacks.

// 1. Scope & loop closure difference
function demonstrateScope() {
  for (var i = 0; i < 3; i++) {
    // var leaks outside the for-block into the whole function
  }
  console.log("After var loop, i =", i); // 3

  for (let j = 0; j < 3; j++) {
    // let is scoped strictly to each block/iteration
  }
  // console.log(j); // ReferenceError: j is not defined
}

// 2. Hoisting and Temporal Dead Zone (TDZ)
function demonstrateHoisting() {
  console.log(hoistedVar); // undefined
  var hoistedVar = "ready";

  // Accessing blockLet before its declaration line throws ReferenceError (TDZ)
  // console.log(blockLet);
  let blockLet = "initialized";
}

// 3. const prevents reassignment, NOT object/array mutation
const userConfig = { theme: "dark", retries: 3 };
userConfig.retries = 5; // Allowed: mutating a property on the object
console.log("Updated retries:", userConfig.retries);

// userConfig = { theme: "light" }; // TypeError: Assignment to constant variable
  • Why const does not freeze objects: const locks the variable binding (the reference stored in that identifier), not the contents of a heap object or array. Use Object.freeze() if you also want shallow immutability on an object.
  • Why TDZ helps catch bugs: Accessing a let or const variable before its declaration fails loudly instead of silently reading undefined.

3. Common Traps to Avoid

  • Assuming const makes arrays or objects completely immutable: Pushing to a const array or updating a property on a const object works because the binding itself does not change.
  • Using var inside for loops with timers/callbacks: A single function-scoped var index can cause every callback to see the final loop value unless captured properly, whereas let creates a fresh binding per iteration.
  • Using let when a variable never gets reassigned: Prefer const by default so readers immediately see a binding stays constant throughout its block.

TL;DR: var is function-scoped, redeclarable, and hoists as undefined; let and const are block-scoped, non-redeclarable in the same scope, and stay in the Temporal Dead Zone until initialized; const requires an initial value and blocks reassignment (though objects/arrays referenced by const can still be mutated).

Are you tracking down a loop/closure or hoisting bug in existing code, or setting style guidelines for a new JavaScript codebase?