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.
var count = 0; var a = 1, b = 2, c;
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
varinsideif,foror{ }is visible in the whole function. Only a function body (or a module or script top level) creates a newvarscope. - Hoisting. The declaration is processed before any code in the scope runs, so reading the variable early gives
undefinedrather than an error. The assignment stays where you wrote it. - Redeclaration. Declaring the same name twice with
varis allowed and does not reset the value unless an initializer is present.letandconstforbid it. - Global object. A top-level
varin a classic script becomes a property ofglobalThis(in browsers, ofwindow). In modules and in Node.js files it stays local to the module.letandconstnever create global properties. - Loops and closures. One
varloop variable is shared by every iteration, which causes the well-known "all callbacks see the last value" bug. Aletloop variable is created fresh per iteration. - Strict mode does not change
varitself, but assigning to an undeclared name (a missingvar) becomes aReferenceErrorinstead of silently creating a global. - Recommendation. Prefer
const, useletwhen you must reassign, and keepvaronly when maintaining legacy code.
Browser support
Supported in every JavaScript engine ever shipped.