The var Keyword
var is the old way to declare variables — usually avoid it.
Syntax
var x = 5;var is the original way to declare variables. In modern code you should prefer let and const.
Why avoid var?
varis function-scoped, not block-scoped, which can cause surprising bugs.vardeclarations are hoisted and can be redeclared, hiding mistakes.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Understand legacy code that uses var throughout a jQuery-era codebase.
- Diagnose a bug where a var variable leaks out of an if-block and overwrites a value unexpectedly.
- Explain why a for-loop using var requires a closure to capture the index correctly in async callbacks.
More examples
var is function-scoped not block-scoped
Demonstrates var's function scope: the variable is accessible outside the if-block where it was declared.
if (true) {
var message = "I leak out";
}
console.log(message); // "I leak out" – visible outside the blockvar hoisting
Shows that var declarations are hoisted to the top of their function, logging undefined before the assignment.
console.log(score); // undefined – hoisted, not initialised yet
var score = 42;
console.log(score); // 42var in loop closure pitfall
Illustrates the classic var-in-loop closure bug where all callbacks share the same hoisted variable.
const funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(() => console.log(i));
}
funcs[0](); // 3 – all share the same i
funcs[1](); // 3
Discussion