JavaScript Execution Context

JavaScript engines create execution context objects (ECOs) anytime a function is invoked. For client side JavaScript, everything inside the script tag is in the global EC. The EC is composed of everything that occurs while the function is executing and involves two passes over the code.

Example 1. Execution context object – first pass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
foo(1);
// An empty execution context object is created when foo is invoked
// {} <-- Execution context object  
                   
function foo(arg) {
  // Function arguments are declared and assigned
  // { arg: 1}

  var local_var = 'baz';
  // Local variables are declared BUT NOT assigned
  // { arg: 1, local_var: undefined }

  function bar(){        
    console.log('bar');
  }
  // Functions are declared and assigned but not executed
  // {  arg: 1,
  //    local_var: undefined,
  //    bar: function() {
  //      console.log('bar');
  //    }
  // }
  bar();
// Nothing happens as code is not executed on first pass!
}

At this point, arguments and functions have been declared and assigned, and local variables have been declared. It is now time for the JavaScript engine to perform its second pass over our code.

Example 2. Execution context object – second pass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
foo(1);              
// {
//    arg:1,
//    local_var: undefined,
//    bar: function() {
//      console.log('bar');
//    }
// }                              

function foo(arg) {
  // Local variables are assigned to ECO
  // as code is executed        
  var local_var = 'baz'

  // {
  //    arg:1,
  //    local_var: 'baz',
  //    bar: function() {
  //      console.log('bar');
  //    }
  // }  

  function bar(){        
    console.log('bar');  
  }
                   
  bar();
  // The attributes representing variables on this ECO
  // remain the same; when bar is invoked, a new ECO
  // is created inside this one
}

Reference:
Mikowski, Michael S., and Josh C. Powell. Single Page Web Applications: JavaScript End-to-end. Shelter Island, NY: Manning, 2013. Print.