Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The var statement

Reference for the JavaScript var statement: function scope, hoisting, redeclaration, global properties and why let and const are usually better.

The var statement declares a variable and optionally gives it a starting value. It is the original way to declare variables in JavaScript. A var variable belongs to the nearest enclosing function (or to the global scope), not to the nearest block, and its declaration is hoisted: the name exists from the start of that scope, with the value undefined until the assignment runs.

Modern code uses let and const instead, because block scope and the "temporal dead zone" catch mistakes that var hides. You still meet var in older code, so you need to understand it.

JavaScript
var count = 0;
var a = 1, b = 2, c;

Try it

JS Function scope and hoisting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS The classic loop closure bug

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
var name1;
var name1 = value1;
var name1 = value1, name2 = value2, nameN;
var { a, b } = object;      // destructuring
var [first, second] = list;
Part Description
name A valid identifier, or a destructuring pattern.
value Any expression. Without an initializer the variable is undefined.

Exceptions: none at declaration time. Reading a name that was never declared throws a ReferenceError.

Usage notes

  • Function scope. A var inside if, for or { } is visible in the whole function. Only a function body (or a module or script top level) creates a new var scope.
  • Hoisting. The declaration is processed before any code in the scope runs, so reading the variable early gives undefined rather than an error. The assignment stays where you wrote it.
  • Redeclaration. Declaring the same name twice with var is allowed and does not reset the value unless an initializer is present. let and const forbid it.
  • Global object. A top-level var in a classic script becomes a property of globalThis (in browsers, of window). In modules and in Node.js files it stays local to the module. let and const never create global properties.
  • Loops and closures. One var loop variable is shared by every iteration, which causes the well-known "all callbacks see the last value" bug. A let loop variable is created fresh per iteration.
  • Strict mode does not change var itself, but assigning to an undeclared name (a missing var) becomes a ReferenceError instead of silently creating a global.
  • Recommendation. Prefer const, use let when you must reassign, and keep var only when maintaining legacy code.

Browser support

Supported in every JavaScript engine ever shipped.