Table of contents
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 functiona()
.When compiler see's the function
a()
an execution context is stacked onto global execution context in call stack which has variablea
, functionb()
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 variableb
,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 functiona()
).When compiler reach to
console.log(a + " is from function a()");
it search for variablea
in it's local environment but didn't find it so it goes to it's parent and finds variablea
and prints 10 from function a() and moves to next lineconsole.log(g + " is global execution context");
and starts searching variableg
in local environment but unable to find then it search in functiona()
and unable to find, then it goes to parent of functiona()
which is global execution and findsg
and prints30 is in global execution context
and then functionb()
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