The Scope Chain

The Scope Chain

Whenever a javascript code begins it's execution a global execution context is set up first in the call stack(call stack in simple words is a stack of functions that has to be executed the first function that enters the stack will be completed at the last). The global execution context consist of all the global variables and functions. And whenever a function is in invoke a new execution context is added in the call stack.

Lexical Environment

let me also introduce you to lexical environment, lexical environment is created whenever an execution context is created it consist of local environment and reference to lexical environment of parent.

lexical environment = local environment + reference to parent environment

Scope Chaining

function a(){
    let a = 10;
    function b(){
        let b = 20;
        console.log(a + " is from function a()");
        console.log(g + " is in global execution context");
    }
    b();
}
let g = 30;
a();
// 10 is from function a()
// 30 is in global execution context

so in the above code when code begins it's execution:

  • A global execution context is set up in call stack which contain variable g and function a().

  • When compiler see's the function a() an execution context is stacked onto global execution context in call stack which has variable a, function b() and has it's own lexical environment( local environment and reference to parent global execution context).

  • When compiler reach to function b() another execution context is stacked in call stack which has variable b, console.log(a + " is from function a()"); console.log(g + " is global execution context"); which has it's own lexical environment( local environment and reference to parent function a()).

  • When compiler reach to console.log(a + " is from function a()"); it search for variable a in it's local environment but didn't find it so it goes to it's parent and finds variable a and prints 10 from function a() and moves to next line console.log(g + " is global execution context"); and starts searching variable g in local environment but unable to find then it search in function a() and unable to find, then it goes to parent of function a() which is global execution and finds g and prints 30 is in global execution context and then function b() completes the task and get removed from call stack.

  • function a() also gets removed from call stack and eventually our code ends. This chaining is called Scope Chaining

1.png