Difference between var and let in JavaScript:
-
Scope
var→ Function-scoped (accessible throughout the function).let→ Block-scoped (accessible only inside{ }).
✅ Example:
if (true) { var x = 10; let y = 20; } console.log(x); // ✅ 10 console.log(y); // ❌ ReferenceError
-
Hoisting
varis hoisted and initialized withundefined.letis hoisted but not initialized (in temporal dead zone until declared).
✅ Example:
console.log(a); // ✅ undefined var a = 5; console.log(b); // ❌ ReferenceError let b = 10;
-
Redeclaration
var→ Can be redeclared in the same scope.let→ Cannot be redeclared in the same scope.
✅ Example:
var name = "Dev"; var name = "John"; // ✅ Allowed let age = 25; let age = 30; // ❌ Error: Identifier 'age' has already been declared
-
Global Object Property (
windowin browsers)var→ Attaches towindowobject when declared globally.let→ Does not attach towindow.
✅ Example (in browser console):
var city = "Delhi"; let country = "India"; console.log(window.city); // ✅ "Delhi" console.log(window.country); // ❌ undefined
- Best Practice
- Use
let(orconst) instead ofvar→ safer, block-scoped, avoids accidental bugs.
- Use
🔹 Quick Comparison Table
| Feature | var 🟢 |
let 🔵 |
|---|---|---|
| Scope | Function-scoped | Block-scoped |
| Hoisting | Hoisted, initialized with undefined |
Hoisted, TDZ until declaration |
| Redeclaration | Allowed | ❌ Not allowed |
| Reassignment | Allowed | Allowed |
| Global Object (window) | ✅ Adds to window | ❌ Doesn’t add |
| Best Use Case | Legacy code | Modern JS (ES6+) |
✅ Short Interview Answer
“
varis function-scoped, hoisted withundefined, and can be redeclared.letis block-scoped, hoisted but in the temporal dead zone, and cannot be redeclared. Best practice is to useletorconstin modern JavaScript to avoid bugs.”