Table of contents
Execution context is the most important thing to understand in javascript. after you understand this then understand Hoisting, Temporal dead zone, Functions, Scoops, etc is just a piece of cake.
When javascript executes any code then a Global execution context is created and under Global execution context code executed in Two Phases
- Memory allocation Phase
- Code Execution Phase
Example Code
1 let a = 10;
2 function SquearOf(num){
3 return a*a
4 }
5
6 let result = SquearOf(a)
7 console.log(result)
1. Memory allocation Phase
In this phase, javascript assigns memory in key-value pair.
In the case of variable The key is variable name
and value is **undefined**
, and In the case of functions key isfunction name
and value is the **whole codeBase under the function query brackets.**
From the code example, the memory allocation phase looks like this
2. Code Execution Phase
In this phase, code executes line by line. In the upper code example, the code executes like this
- Assign 10 to variable
a
( line 1 ) - For now, javascript has nothing to do with the function part, so javascript skips that part ( skips lines 2, 3, and 4 )
- In line no 6 javascript call
SquearOf
and assign the value in variableresult
( line 6 ) - And at last, it console log the
result
Attention:
In the 6th line when javascript calling function SquearOf()
There another execution context is created.
Under this function execution context code run in two phases -> 1) memory allocation , and 2) code execution
And now The Global context looks like this
After all the function code is executed, then that function execution context removed
CallStack
Still now whatever is happening - global execution context created, under global execution context code executed in two phases, memory allocation phase, code execution phase, this all happened in CallStack
You can imagine CallStack like this
When any javascript code run then a global execution context is created in CallStack and
when we invoke or call
any function then in callstack another function execution context created
after javascript finishes or executed all code under that function, then from callstack that function execution context got removed
In This example you can see, how execution happened in CallStack -->
Example Code
1 let a = 10;
2 function SquearOf(num){
3 return a*a
4 }
5
6 let result = SquearOf(a)
7 console.log(result)
When code starts executed then a global execution context is created and then when a function call happened then a function execution context created
After the function done executed then it is removed from callStack and after all the code is executed the global execution context is removed from callstack.
Thank you for reading. I hope it will help you in your javascript journey ๐๐