Yatendra Sharma
2 min readMay 20, 2021

How JavaScript code is executed??

Do you really know how JavaScript code is executed? How global execution context is created? What is happening behind the scenes when you run your JavaScript code?

So, if you have the answers to the above questions that's great but if not you can read this post it will clear everything that is going on behind the scenes when you run your JavaScript Code.

Now if you think when you run your JavaScript code it will be executed in one go then you might be missing something very interesting which happens behind the scenes.Let us take an example & see how it works!

As we can see from above code there are variables & functions present in it so what actually happens is whenever we run this code a “global execution context” is created.Global execution context is nothing but a container.There are two phase:

i)Memory creation phase

ii)Code execution phase

In “memory creation phase” whole JS code is executed & variables get assigned a special keyword “undefined” in memory creation phase while functions are copied as it is present in memory.In our case there are three variables & one function i.e x,cube1,cube2 & cube respectively.So all the variables assigned with a special keyword “undefined” & for function whole code is copied as it is.

Now comes the code execution phase again JS code is executed line by line when our first line of code encounters it will see a value of “2” in x then the special keyword “undefined” is replaced by 2.There is nothing to execute because function is present as it is in memory.

Here comes the tedious part when JS code encounters with line 6 of code cube function gets invoked & now again an “execution context” is created inside the code execution phase itself now it will take variables as the parameter of function & the actual variable present in function block.In the similar manner as above all variables will be first assigned a special keyword “undefined”.So here y & ans will assign undefined in memory creation phase.Now when it comes to code execution phase because ‘x’ is passed as an argument to the function it will replace undefined with value of ‘x’ i.e 5 & ans will be replaced by 125 (cube of 5).

In the similar manner as above same things happen & a new execution context is created,each variable & function assigned the value in similar manner.

Now when everything is done all the execution context are deleted or pop of from the call stack.

It might not be easy to digest this thing which is going on behind the scenes but this is exactly how JavaScript code is executed.

Thanks for reading this out.

Any feedbacks are really appreciated.

No responses yet