var Redirect 1

Summary

Declares a variable, optionally initializing it to a value.

Version Information

Statement
Implemented in: JavaScript 1.0, NES 2.0
ECMA Version: ECMA-262

Syntax

var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];

Parameters

varnameN
Variable name. It can be any legal identifier.
valueN
Initial value of the variable. It can be any legal expression.

Description

The scope of a variable declared with var is the enclosing function or, for variables declared outside a function, the global scope (which is bound to the global object).

Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a property of the global object). The difference is that a declared variable is a non-configurable property of the global object while an undeclared is configurable.

var a = 1;
b = 2;

delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise.
delete this.b;

console.log(a, b); // Throws a ReferenceError. Since the 'b' property doesn't exist in the global object,
// the 'b' variable stops being a variable

Consequently, it is recommended to always declare your variables, regardless of being in the global scope or in a function

Failure to declare the variable in these cases will very likely lead to unexpected results. For that reason, in ECMAScript 5 strict mode, assigning a value to an undeclared variable inside a function throws an error.

var hoisting

In JavaScript, a variable can be declared after being used.

bla = 2
var bla;
// ...

// is implicitly understood as:

var bla;
bla = 2;

For that reason, it is recommended to always declare variable at the top of functions.

Examples

Declaring and initializing two variables:

var a = 0, b = 0;

Assigning 2 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 is declared. y declaration (but not initialisation!) is hoisted
// so, at the time of "x = y", y is declared (no ReferenceError is thrown) and its value is 'undefined'
// then, y is assigned its value.
// Consequently, after the first line, x === undefined && y === 'A'. Hence the concatenation

Be careful of initialization of several variables:

var x = 0;

function f(){
  var x = y = 1; // x is declared locally. y is not!
}
f();

console.log(x, y); // 0, 1
// x is the global one as expected
// y leaked outside of the function, though!

See also

Document Tags and Contributors

 Last updated by: Sheppy,