var (Declaration)

A variable declarator.

Availability:

ECMAScript edition - 2
JavaScript - 1.0
JScript - 1.0
Internet Explorer- 3.02
Netscape version - 2.0
Netscape Enterprise Server - 2.0
Opera - 3.0
JavaScript syntax:-var anIdentifier
-var anIdentifier = anInitialValue
-var anIdentifier = anInitialValue, anIdentifier = anInitialValue, ...
-var anIdentifier, anIdentifier, ...
Argument list:anIdentifierThe name of a variable.
anInitialValueAn initial value for the variable

The var keyword prefaces a list of variable declarations. The list is terminated by a semi-colon.

Variables can be initialized in the declaration list that can declare a single variable or several at once.

If the var statement occurs inside a function declaration, the variables are defined with a scope that is local to that function body. Otherwise they are defined with global scope and are created as members of the Global object. When they are created as global variables, they take on the DontDelete property attributes.

Variables are created when an execution scope is entered. A block does not indicate a new execution scope, so variables cannot be created local to a code block unless it is a function body. That means they are not local to an if(), while() or for() block of compound statements.

When variables are created, they are initialized to contain the value undefined. If an initializer is added to the variable declaration, the value is assigned when the var statement is executed, which may be some time after the execution scope has caused the variable to be created.

Warnings:

Example code:

   <HTML>
   <HEAD>
   </HEAD>
   <BODY>
   <SCRIPT>
   var myGlobalVariable = 100;
   function mLocalScope()
   {
   var myLocalVariable = 200;
   }
   </SCRIPT>
   </BODY>
   </HTML>

See also:= (Assign), Assign value (=), Assignment expression, Assignment operator, Comma operator (,), Compound statement, function( ... ) ..., Global object, Initialisation, Semi-colon (;), Statement, Variable Declaration, Variable statement

Cross-references:

ECMA 262 edition 2 - section - 10.1.3

ECMA 262 edition 2 - section - 12.2

ECMA 262 edition 3 - section - 10.1.3

ECMA 262 edition 3 - section - 12.2