How JavaScript Code is Executed???

Do you know when you run a Javascript program there are a lot of things happening behind the scenes inside the JS engine!!!

As seen in the previous blog we know that "Everything in JS happens in the execution context."

  • We will see all these with the help of an example.
  • So, whenever a program starts executing it gets processed into the Memory creation phase and Code execution phase.
  • Memory creation phase is a very important and critical phase.
  • In the memory creation phase i.e., the first phase it just allocates memory space to variables & functions.
  • variables will store “undefined” to it. Undefined is a special keyword.
  • functions will be stored with all the code in it as it is. So, it will copy the code which is in function and will store it.
  • So after the first phase gets over, the Execution Context for the code below would look like the image shown
var n = 2;
function square (num) {
          var ans = num * num;
          return ans;
}
var square2 = square(n);
var square4 = square(4);

image.png

  • In the code execution phase i.e., the second phase it will allocate the value which is in code to the variable.
  • In the case of function invocation in the second phase, it will create a brand-new execution context in the “code” component. And it will have both memory & code components in it as shown in the image below.
    image.png
  • It will again repeat the same procedure again until the function gets executed.
  • After the function execution is over, the execution context gets deleted. This is true for the global execution context too.
  • return is a special keyword that tells the function that you are done with your work, just return the whole control back to the execution context where the function was invoked.
  • For every function invocation, a new execution context is created every time.
  • To manage execution contexts, JS uses “Call Stack”.
  • “Call stack maintains the order of execution of execution contexts”.
  • Every time at bottom of this stack, JS stores GEC (Global Execution Context).
  • So, whenever a program starts executing a call stack is created, and inside it, GEC is pushed. And whenever a function is invoked, EC (Execution Context) gets created and it gets pushed into the call stack.
  • Once function execution is over it gets deleted and popped out of the call stack. So, the control gets back to GEC. And when GEC also gets executed it gets deleted and popped out of the call stack and the call stack gets empty. So, this is how the whole code inside the EC is executed.
  • A huge shoutout to Akshay Saini as he helped me to understand all these things and also to Tanay Pratap as he inspired me to write blogs.