Chapter II · Variables & Values
The var Keyword
The var keyword is JavaScript’s legacy variable declaration mechanism, scoped to functions rather than blocks.
01 What is var?
var is the original way variables were declared in JavaScript before ES6. Unlike let and const, var is function-scoped (or globally scoped if declared outside a function) and ignores block boundaries entirely.
Variables declared with var are hoisted to the top of their execution scope and initialized automatically with undefined.
02 Simple Example
Demonstrating function scoping and block leakage with var.
function test() {
if (true) {
var leaked = "I leak out!";
}
console.log(leaked); // "I leak out!" because var ignores blocks
}
test();
Because var ignores if blocks, leaked is accessible anywhere inside the surrounding function.
03 How It Works
During the creation phase of an execution context, var declarations are registered on the variable environment and initialized with undefined.
Var declarations attach to function or global variable environments during context creation.
04 Step-by-Step
The engine enters an execution context.
All
vardeclarations are hoisted and initialized toundefined.Code execution reaches the line where the
varstatement appears.The variable is updated with its assigned value.
05 Mental Model
"A megaphone announcement that echoes across the entire room, ignoring walls and closed doors."
It spreads across the entire function scope rather than staying confined to local code blocks.
06 Common Mistakes
The classic var-in-a-loop bug:
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Logs 4, 4, 4 — every callback shares the same "i"
for (let j = 1; j <= 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Logs 1, 2, 3 — "let" creates a fresh binding each iteration
Best practice: there's essentially no reason to write var in new code. Modern style guides (Airbnb, StandardJS, ESLint's no-var rule) all recommend let/const exclusively; you'll mostly encounter var when reading older codebases.
07 Interview Questions
Q: Why is var considered legacy in modern code?
It's function-scoped rather than block-scoped, gets hoisted with an undefined default (masking bugs), and can be redeclared silently — all sources of subtle errors that let/const fix.
Q: What's a classic var bug in loops?
Using var i in a for loop with an async callback — all callbacks share the same i, so they all see its final value, unlike let which creates a fresh binding per iteration.
Key Takeaway
The var keyword is legacy syntax with function scope and hoisting quirks; modern JavaScript heavily prefers let and const.