Availability: |
| ||||||||
JavaScript syntax: | - | var anIdentifier | |||||||
- | var anIdentifier = anInitialValue | ||||||||
- | var anIdentifier = anInitialValue, anIdentifier = anInitialValue, ... | ||||||||
- | var anIdentifier, anIdentifier, ... | ||||||||
Argument list: | anIdentifier | The name of a variable. | |||||||
anInitialValue | An 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.
If you fail to declare a variable with the var keyword, you will end up creating a global variable automatically. If the variable should only have local scope and duration within a function, then you may want to avoid this.
You should use local variables as often as possible to avoid unwanted side effects.
<HTML> <HEAD> </HEAD> <BODY> <SCRIPT> var myGlobalVariable = 100; function mLocalScope() { var myLocalVariable = 200; } </SCRIPT> </BODY> </HTML>
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
Prev | Home | Next |
valueOf() | Up | VAR object |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |