This project has moved. For the latest updates, please go here.

Syntax of variable declaration

Define variables using following syntax:
[var] identifier[ = expression] [, identifier[ = expression]]*;

  • 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

Declaration list

Variables will be declared in same scope if they were specified with var keyword.
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

// a new inner call-scope will be created and pushed into call-stack
// then body of function will be executed
function() {
  var a = 10;       // 'a' is declared in inner call-scope 
  return a;         // value of 'a' will be returned 
} ();               // perform calling, inner call-scope destroyed and popped
                    // 'a' belongs to inner call-scope so 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

Scope Access

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);


The result is:
  a = 20

Global Object

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.

See Also

Last edited Jan 28, 2014 at 4:03 PM by unvell, version 7