The var Keyword

var is the old way to declare variables — usually avoid it.

Syntaxvar x = 5;

var is the original way to declare variables. In modern code you should prefer let and const.

Why avoid var?

  • var is function-scoped, not block-scoped, which can cause surprising bugs.
  • var declarations are hoisted and can be redeclared, hiding mistakes.

Example

Try it yourself
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.

Example · js
if (true) {
  var message = "I leak out";
}
console.log(message); // "I leak out" – visible outside the block

var hoisting

Shows that var declarations are hoisted to the top of their function, logging undefined before the assignment.

Example · js
console.log(score); // undefined – hoisted, not initialised yet
var score = 42;
console.log(score); // 42

var in loop closure pitfall

Illustrates the classic var-in-loop closure bug where all callbacks share the same hoisted variable.

Example · js
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

  • Be the first to comment on this lesson.