The var statement declares a variable, optionally initializing it to a value.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

Initial value of the variable. It can be any legal expression. Default value is undefined.

Description

var declarations, wherever they occur, are processed before any code is executed. This is called hoisting, and is discussed further below.

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:

1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

var hoisting

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.

It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached:

Examples

Declaring and initializing two variables

Assigning two variables with single string value

var a = 'A';
var b = a;
// Equivalent to:
var a, b = a = 'A';

Be mindful of the order:

var x = y, y = 'A';
console.log(x + y); // undefinedA

Here, x and y are declared before any code is executed, but the assignments occur later. At the time "x = y" is evaluated, y exists so no ReferenceError is thrown and its value is undefined. So, x is assigned the undefined value. Then, y is assigned the value 'A'. Consequently, after the first line, x === undefined && y === 'A', hence the result.