-
Notifications
You must be signed in to change notification settings - Fork 35
Variables
Jing Lu edited this page Jun 14, 2013
·
9 revisions
Define variables using following syntax:
[var] identifier[ = expression] [, identifier[ = expression]]*;
where
- var keyword used to specify whether the variable is required to declare in current call-scope.
- identifier is name of variable, composed by digits, letters, $ and _.
- expression used to initialize variable. The value of expression will be evaluated immediately, or a null will be set to variable if expression is ignored.
For example:
var a = 10; // declare 'a' in current call-scope, and set 'a' to 10
var b; // declare 'b' in current call-scope, 'b' is null
Variables are declared in same scope when var keyword is specified.
var c = 20, d; // declare 'c' and 'd' in current call-scope, and set 'c' to 20 and 'd' to null
A call-scope is a session of function calling, which be created from function calling and destroyed at calling is finished.
For example, assume that 'hello' function exists in script:
function hello() {
var a = 10;
return a;
}
When we to call this function using hello()
:
// root call-scpoe
hello();
// a new inner call-scope will be created and pushed into call-stack
// then body of function will be executed
{
var a = 10; // 'a' is declared in inner call-scope
return a; // value of 'a' will be returned
} // calling is finished, inner call-scope will be destroyed and popped
// 'a' belongs to inner call-scope will also be destroyed
// root call-scope is resumed
var c = hello(); // return value copied to 'c'
var d = a; // 'd' will be null since no 'a' here
All variables declared in outer scope could be available to inner scope.
var a = 10, b = 5;
function hello() {
return a + b; // access 'a' and 'b' from outer scope
}
var c = hello(); // 'c' is 15
A variable declared with var keyword in inner scope will always overrides a variable that declared in outer scope. For example:
var a = 10;
function hello() {
var a = 20;
console.log('a = ' + a);
}
hello();
The result is:
a = 20
Variables declared in most outer scope will be stored as property to global object, that could be used as global variable.
var a = 10;
function hello() {
var b = a + 5; // 'a' is global variable
return b;
}
var c = hello(); // 'c' is 15
See GlobalObject.