Hello Readers,
Did you Ever wonder what happens when JS Code is Executed. Read below to Find out More:
- First of all, Everything in JavaScript happens inside an Execution Context(EC). So what is this EC???
- Lets Consider the below Example:
1. var number=2;
2. function Square(number){
3. var answer=number*number;
4. return answer;
5. }
6. var SquareTwo=Square(2);
7. var SquareFour=Square(4);
- When we run the above program, A Global Execution Context is initially Created which consists of 2 phases ie Memory Creation phase and Code Execution Phase.
- Memory Creation Phase : Here JS will allocate some memory to all the variables (as Undefined) and Functions are stored as Functions. For Example, variable number will be undefined and square function will have same function etc.
-
Code Execution Phase : Here once again JS runs line by line and assigns original value to respective variables.
For Example, variable
var number= 2
is assigned etc.
- But when it arrives at line 6 , Function invocation happens and As a result A New Execution Context is created ie
- The same Memory Creation phase and Code Execution Phase is followed inside this newly created Execution Context and after all the respective calculated values are assigned , This EC will be automatically deleted.
- Here a Problem arises that Inside Functions, There is a possibility of having many Execution Contexts like the below :
- To resolve this, Call Stacks were discovered : Call Stack maintains the order of Execution of Execution Contexts.
- Here First EC4 is resolved and Deleted and similar process to be followed until EC1 gets deleted and the program finishes .
- This is how JS works, Thanks for Reading my Blog Folks :)
Top comments (1)
const and let are not hoisted line var. So those variables are not undefined at start, but does not exists at all.