var
varis the old way to declare variables. It’s still widely used in legacy code, but modern JavaScript prefersletandconst.
Why Do We Need This?
Section titled “Why Do We Need This?”Many codebases still use var. Understanding it is essential for:
- Maintaining legacy code
- Understanding why
letandconstwere created - Passing interview questions about hoisting and scope
Real World Example
Section titled “Real World Example”// Old codebase from 2010 — everything was varvar userName = "Alice";var userAge = 30;var isAdmin = true;Visual Explanation
Section titled “Visual Explanation”flowchart TD subgraph Scope["var is Function-Scoped"] A["function test() {"] --> B["var x = 1"] B --> C["if (true) {"] C --> D["var y = 2 ← Same function scope"] D --> E["}"] E --> F["console.log(y) // 2 ← Accessible!"] F --> G["console.log(x) // 1"] end
style Scope fill:#1e3a5f,color:#fffKey Characteristics
Section titled “Key Characteristics”| Feature | Behavior |
|---|---|
| Scope | Function-scoped (not block-scoped!) |
| Hoisting | Hoisted, initialized as undefined |
| Redeclaration | ✅ Allowed |
| Global property | Becomes property of window (browser) |
| Block scope | ❌ Ignores {} blocks |
Code Examples
Section titled “Code Examples”// 1. Function-scoped — NOT block-scopedfunction example() { if (true) { var message = "Hello"; // var ignores block } console.log(message); // "Hello" — accessible!}example();
// Compare with let:function example2() { if (true) { let message = "Hello"; // let respects block } console.log(message); // ❌ ReferenceError}
// 2. Hoistingconsole.log(x); // undefined (not an error!)var x = 5;
// This is how JavaScript sees it:// var x; ← hoisted (initialized as undefined)// console.log(x); ← undefined// x = 5; ← assignment stays
// 3. Redeclaration is allowedvar count = 1;var count = 2; // ✅ No errorconsole.log(count); // 2
// 4. Global scope — attaches to windowvar globalVar = "I'm global";console.log(window.globalVar); // "I'm global" (browser)The Classic var Bug
Section titled “The Classic var Bug”// This is the #1 reason var is avoided:for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Output: 3, 3, 3 (NOT 0, 1, 2!)// Reason: var is function-scoped, so there's only ONE `i`
// Fix with let:for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Output: 0, 1, 2 ✅⚠ Common Mistakes
Section titled “⚠ Common Mistakes”// ❌ Assuming var is block-scoped{ var x = 10;}console.log(x); // 10 ← leaks out of block!
// ❌ Redeclaring accidentallyvar apiKey = "prod-123";// ... 100 lines later ...var apiKey = "dev-456"; // No error! Bug introduced silently🚀 Best Practices
Section titled “🚀 Best Practices”- Never use
varin modern code — useletorconst - Understand
varfor legacy code maintenance - If you see
varin code reviews, suggest replacing withlet/const
🎯 Interview Tip
Section titled “🎯 Interview Tip”Q: “What happens when you use
varinside aforloop withsetTimeout?” A: “All callbacks share the samevarvariable becausevaris function-scoped. By the time the callbacks run, the loop has finished andiis at its final value. Usingletfixes this becauseletis block-scoped and creates a new binding for each iteration.”
✅ Summary
Section titled “✅ Summary”| Feature | var |
|---|---|
| Scope | Function |
| Hoisting | ✅ (initialized as undefined) |
| Redeclare | ✅ Allowed |
| Window property | ✅ window.x |
| Modern usage | ❌ Avoid |
🔗 Related Topics
Section titled “🔗 Related Topics”- let — The modern alternative
- const — Constant declarations
- Temporal Dead Zone — Why
let/constbehave differently