Execution Context And Scope in Javascript

Description

The execution context of a variable or function defines the scope of the function and variables.

The global execution context is the outermost one.

In web browsers, the global context is the window object, all global variables and functions are created as properties and methods on the window object.

Each function has its own execution context.

Example

The following code defines a variable name outside the function. We can change its value in a function and the value persist out of the function scope.


var name = "blue"; 
function changeName(){ //from w w w  .java  2s. com
    if (name === "blue"){ 
        name = "red"; 
    } else { 
        name = "blue"; 
    } 
} 
changeName(); 
console.log(name);//red

The code above generates the following result.

Example 2

The following code has three level of execution context:


var name = "JavaScript"; 
function changeName(){ /*from   w  w w  . ja  va2 s.com*/
   var anotherName = "HTML";
   function swapNames(){ 
      var tempName = anotherName; 
      console.log("tempName:"+tempName);
      anotherName = name; 
      name = tempName;
      //name, anotherName, and tempName 
      //are all accessible here 
   }
   //name and anotherName are accessible here, 
   //but not tempName 
   swapNames(); 
} 
//only name is accessible here 
changeName(); 
console.log(name);//HTML        

The code above generates the following result.

Example 3

JavaScript has no block-level scopes.


if (true) { /*from  w ww.  ja  va 2  s. co  m*/
   var color = "blue"; 
} 
console.log(color); //"blue" 

for (var i = 0; i < 10; i++){ 
   console.log(i); 
} 
console.log(i); //10 

The code above generates the following result.

var

When a variable is declared using var, it is added to the current context.


function add() { /*from   w w  w. j  ava2  s .c om*/
  var color = 'blue'; 
} 
console.log(color);//error

Without var keyword variable is globe scoped.


function add() { /*from   w w w  . jav a 2s  .  c  om*/
  color = 'blue'; 
} 
console.log(color);//blue





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions