Execution Context And Scope

The execution context of a variable or function defines the scope of the function and variables. The global execution context is the outermost one. Each function has its own execution context.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var name = "blue"; 
        
        function changeName(){ 
            if (name === "blue"){ 
                name = "red"; 
            } else { 
                name = "blue"; 
            } 
        } 
        changeName(); 
        document.writeln(name);//red

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The following code has three level of execution context:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var name = "JavaScript"; 
        function changeName(){ 
           var anotherName = "HTML";
           function swapNames(){ 
              var tempName = anotherName; 
              document.writeln("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(); 
        document.writeln(name);//HTML        
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Variables:
  1. Primitive and reference values
  2. Determining Type: typeof vs instanceof
  3. Execution Context And Scope
  4. No Block-Level Scopes
  5. Variable Declaration with var