Before we start exploring and understanding scope chain let's understand lexical environment and execution context in JavaScript.

Lexical Environment:

Lexical Environment exists in code you write and what matters most is where is your code sitting physically.

Execution Context:

It helps to manage the code that is running. There exist a global execution context which is created once a javascript code in executed by the browser.

Also whenever a function is called or invoved a new execution context is created and put on the execution stack.

Let's see an example code:

function a(){
   var result = "a_scoped_result"
   b();   
}
function b(){
   console.log(result);  
}
          
var result = "global_scoped_result";
a();
 

 

The execution stack created for the above code is described below:

Run the above JavaScript code to understand the scope chain, let's go through it with explanation.

#9 has a variable result defined with value set to global_scoped_result which is global scoped.

#10  function a is invoked , it has a local variable result with value set to a_scoped_result

and function b is invoked from within a.

For many the expected output would be a_scoped_result but the actual output is global_scoped_named. The scope chain is decided lexically which means where the function b is sitting physically within the code.

Since function b is lexically sitting at the global scope if a variable is not found within its execution context it will look into it's outer environment hence the output is global_scoped_named.

If we change the above code to something mentioned below.

 

function a(){
   var result = "a_scoped_result"
   function b(){
     console.log(result);  
   }
   b();   
}

          
var result = "global_scoped_result";
a();
 

 

The result would be a_scoped_result since the function b is lexically sitting inside the function a, so if a variable is not defined within it's scope it would will first look into a then the global scope.

If you comment out #2 from the above code then the scope chain will scan to global context and the output will be global_scoped_result.

Thanks for reading.