As mentioned earlier, a javascript code is executed in two phases, first is memory allocation phase and second is code execution phase.
So we are going to look into both phases step by step. Let's take an example:
function incre(k){
int ans=k+1;
return ans;
}
var i=0;
var first=incre(2);
var second=incre(i);
🔴 Memory Allocation
In this phase, the code will be parsed line by line, allocating memory. In first line when function incre
is encountered the whole function snippet is saved in the memory. Next var i
is stored with a value undefined
. Same happens for both first
and second
.
Once this is done, the next part of the execution is started.
🟢 Code Execution
The program is executed, starting from the first line. As in the above example, it moves to executable code, moving forward from function definition. As soon as it finds var i
, it changes it's value to 0, as indicated.
Next it goes to var first
where there is function invocation. This is where things get interesting.
Before we understand this, You should know that this whole box, whatever is happening is happening in Global Execution context. A function makes it's own execution context whenever it is invoked.
All these contexts are saved in a stack.
So, it goes the func incre
and executes it line by line, in a similar fashion (Two phases). First the memory is allocated and then the code is executed. In the function invocation by first
, it first allocates ans memory and a value undefined
. Then, it is executed and value k+1
is put. As soon as the return statement is encountered the execution context for this invocation is popped out of the stack.
We do the same thing with invocation 2 in second
.
At the end, even the global execution context is popped, hence indication the complete execution of js code.
Top comments (0)