DEV Community

Cover image for How JS is executed & Call Stack
Muskan Chhatrasal
Muskan Chhatrasal

Posted on • Updated on

How JS is executed & Call Stack

Exactly when a JS program is ran, a global execution context is made.The execution setting is made in two phases:-
Memory creation stage - JS will dole out memory to variables and functions.
Code execution stage.

What about we think about the accompanying code and it's execution:

var n = 5;
function square(num){
var ans = num*num;
return back;
}
var sqr2 = square(n);
var sqr4 = square(4);

Indisputably the primary thing which JS does is memory creation stage, so it goes to line one of the above code digit, and award a memory space for variable 'n' and a short time later goes to line two, and allocates a memory space for function 'square'. While disseminating memory for n it stores 'undefined', an exceptional incentive for 'n'. For 'square', it stores the whole code of the capacity inside its memory space. Then, as sqr2 and sqr4 are factors likewise, it assigns memory and stores 'undefined' for them, and this is the completion of first stage for example memory creation stage.

So O/P will look something like

Execution Context Phase 1

By and by, in second stage for instance code execution stage, it starts going through the whole code line by line. As it encounters var n=2, it designate 2 to 'n'. So far, the value of 'n' was indistinct. For function, there is nothing to execute. As these lines were by then overseen in memory creation stage.

Coming to line 6 for instance var sqr2 = square(n), here functions are fairly not equivalent to another dialect. Another execution setting is made by and large. Again in this new execution setting, in memory creation stage, we assign memory to num and ans the two factors. Likewise, undefined is placed in them. As of now, in code execution setting, beginning 2 is named to num. Then, var ans = num*num will store 4 in ans. Starting now and into the foreseeable future, get ans gets the control of program back to where this function was conjured from.

Execution Context Phase 2

Right when return watchword is capable, it returns the control to the called line and moreover the capacity setting is eradicated. Same thing will be reiterated for sqr4 and subsequently after that is done, the worldwide execution setting will be obliterated. So the last chart before deletion would look something like:

Execution Context Phase 2

JavaScript directs code execution setting creation and eradication with the help of Call Stack.

Call Stack

Call stack is a system to screen its place in script that calls different capacities.

Call stack monitors everything of execution context. It is generally called Program Stack, Control Stack, Runtime Stack, Machine stack, Execution Context Stack.

Top comments (0)