References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript var statement

Statement JavaScript All modern browsers Updated
Quick answer

The var keyword is the original, legacy way to declare a variable. It's function-scoped and hoisted, which causes subtle bugs that the block-scoped let and const fixed. In modern code you should use const and let instead — var is mainly something to recognize in older code.

Overview

var is how variables were declared before 2015, and you'll still meet it in older code, so it's worth understanding even though you shouldn't reach for it in new work. The reasons it fell out of favor are the same reasons let and const exist.

Its scoping is the core problem. var is function-scoped, not block-scoped, so a var declared inside an if or for block leaks out to the whole surrounding function. It's also hoisted and initialized as undefined, meaning you can reference it before its declaration line without an error — you just get undefined, which hides bugs rather than surfacing them. And it can be silently redeclared, overwriting an earlier one.

Those behaviors led to a famous class of loop bugs (every callback sharing one leaked var) that let's per-iteration block scope solves cleanly. The bottom line: use const by default and let when you must reassign; treat var as legacy.

Syntax

var x = 1;        // function-scoped, hoisted

function demo() {
  if (true) { var y = 2; }
  return y;  // 2 - var leaked out of the if block
}

// modern: use const / let instead
const a = 1;
let b = 2;

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  function scopeDemo() {
    if (true) {
      var leaked = 'I leaked out';
    }
    return leaked; // accessible - var is function-scoped
  }

  document.getElementById('out').textContent = scopeDemo();
</script>

Best practices

  • Prefer const and let in all new code — avoid var.
  • Recognize var's function scope and hoisting when reading older code.
  • When refactoring, replace var with const (or let if reassigned), checking for scope-leak assumptions.
  • Be wary of var in loops with callbacks — that's the classic shared-variable bug.

Frequently asked questions

What is the difference between var, let and const?
var is function-scoped and hoisted (legacy); let is block-scoped and reassignable; const is block-scoped and can't be reassigned. Use const/let.
Why should I avoid var?
Its function scope leaks variables out of blocks and its hoisting lets you use variables before declaration (as undefined), both of which cause subtle bugs.
What does it mean that var is hoisted?
The declaration is moved to the top of its function and initialized to undefined, so referencing it before its line gives undefined instead of an error.
Is var still supported?
Yes, it works everywhere and isn't deprecated, but modern style uses const and let for safer scoping.