What are the differences between var, let, and const in JavaScript?
❓ Interview Prompt: Compare var, let, and const regarding scope, hoisting, reassignment, and redeclaration.
JavaScript provides three variable declaration keywords with different scoping and mutation rules:
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped ({}) | Block-scoped |
| Hoisting | Hoisted (initialized as undefined) | Hoisted (Temporal Dead Zone) | Hoisted (Temporal Dead Zone) |
| Reassignment | ✅ Yes | ✅ Yes | ❌ No |
| Redeclaration | ✅ Yes (same scope) | ❌ No | ❌ No |
Temporal Dead Zone (TDZ):
let and const are hoisted but cannot be accessed before their declaration line. Accessing them throws a ReferenceError.
Best Practice (2026):
Use const by default. Use let only when reassignment is required. Never use var.
Code Implementation Example
// var is function-scoped (leaks out of blocks)
if (true) { var x = 10; }
console.log(x); // 10 (leaked!)
// let is block-scoped
if (true) { let y = 20; }
// console.log(y); // ReferenceError: y is not defined
// const prevents reassignment
const API_URL = 'https://api.example.com';
// API_URL = 'other'; // TypeError: Assignment to constant
// const objects are mutable (reference is constant, not value)
const user = { name: 'Alice' };
user.name = 'Bob'; // ✅ Allowed (mutating property, not reassigning)Use const by default, let when reassignment is needed. Never use var in modern JavaScript.