DEV Community

Cover image for How javascript code is executed
namitmalasi
namitmalasi

Posted on

How javascript code is executed

Everything in JavaScript happens inside an "Execution Context”. Whenever a JavaScript program is run an execution context is created.

var number=10;  //line1 
function add(n) //line2
{               //line3
var result=n+n; //line4
return result;  //line5
} 

var result1=add(4); //line6
Enter fullscreen mode Exit fullscreen mode

when we run the above code, a global execution context (GEC) is created. It is created in two phases:

1)Creation Phase or Memory Creation

In this phase, javascript allocates the memory to all the variables and functions present in the program. The variables are stored with the value undefined and the function is stored with all the code present in that particular function. For the above code, the variable number is stored with the value undefined and the function add is stored with value b/w the {...} curly braces. The result1 is also a variable so it is stored with the value undefined.

2)Code Execution Phase

In this phase the main execution takes place and the javascript runs through the code line by line. Now the number value is changed from undefined to 10. Then it moves to the next line as there is nothing to execute it moves to line 5. In line 5 function invocation takes place. When a new function is invoked a new execution context is created within the GEC.

Now the again above process is repeated with the two phases but for only the add function. After the function is executed completely, the execution context created for that particular function will get deleted automatically.

Now, when the whole javascript program is executed completely the GEC will also get deleted.

A Call stack is also maintained by javascript. Call stack maintains the "Order of execution of execution contexts". It works similarly as a stack whenever a new function invoked its execution context is pushed into the call stack.
Alt Text
The GEC is at the bottom of the call stack as it is created at the starting of the program and all the new execution context is pushed on top of it. So when a function's execution gets finished its execution context is also removed from the call stack.

Alt Text

I hope you would have found this article beneficial.
Thank you for reading through this article.

Top comments (3)

Collapse
 
sakibsiddiqi15 profile image
Sakib Siddiqi Supto

Is call stack works like "last in last out"?

Collapse
 
namitmalasi profile image
namitmalasi

No, it works on LIFO(last in first out) or FILO(first in last out) similar to the stack data structure.

Collapse
 
namitmalasi profile image
namitmalasi

Thanks👍