DEV Community

Cover image for How JavaScript Code is Executed ?
Naveen Kamath
Naveen Kamath

Posted on

How JavaScript Code is Executed ?

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);
Enter fullscreen mode Exit fullscreen mode
  • 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.

Image description

  • 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.

Image description

  • 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.

Image description

  • But when it arrives at line 6 , Function invocation happens and As a result A New Execution Context is created ie

Image description

  • 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.

Image description

  • Here a Problem arises that Inside Functions, There is a possibility of having many Execution Contexts like the below :

Image description

  • To resolve this, Call Stacks were discovered : Call Stack maintains the order of Execution of Execution Contexts.

Image description

  • 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 :)

Oldest comments (1)

Collapse
 
lyrod profile image
Lyrod

const and let are not hoisted line var. So those variables are not undefined at start, but does not exists at all.