How is Javascript code Executed?
Javascript itself is confusing language most of them said, But, what they didn't say is if you understand GEC(global execution context) well then there is no confusion. Today let see how GEC works under the hood. Before that, I am not a javascript expert I am going to write what I understood from experts.
Global Execution Context
javascript program runs on execution context think like its a container. When you run a javascript program or empty file Global execution context will be created.
It has Two-Component
- Memory allocation Component
- Code Execution Component
Always it's stored as key: value pair in a variable environment.
javascript is single threaded-synchronous which means It executes one command at a time by specific order like one by one.
var n=2;
function square (num){
let ans = num * num;
return ans;
}
var sample = square(n) //4
var sample2 = square(4) //16
The very first thing which JS does is memory creation phase, so it goes to line one of the above code snippet and allocates memory space for variable 'n' and then goes to line two, and allocates memory space for function 'square'. When allocating memory for n it stores 'undefined', a special value for 'n'. For 'square', it stores the whole code of the function inside its memory space. Then, as sample and sample2 are variables as well, it allocates memory and stores 'undefined' for them, and this is the end of the first phase i.e. memory creation phase.
Execution context Phase 1
Now, in the 2nd phase i.e. code execution phase, it starts going through the whole code line by line. As it encounters var n = 2, it assigns 2 to 'n'. Until now, the value of 'n' was undefined. For function, there is nothing to execute. These lines were already dealt with in-memory creation phase. Coming to line 6 i.e. v ar sample = square(n), here functions are a bit different than any other language. A new execution context is created altogether. Again in this new execution context, in the memory creation phase, we allocate memory to num and ans the two variables. And undefined is placed in them. Now, in the code execution phase of this execution context, the first 2 are assigned to num. Then var ans = num * num will store 4 in ans. After that, return ans returns the control of the program back to where this function was invoked from.
Execution context phase2
When the return keyword is encountered, It returns the control to the called line, and also the function execution context is deleted. The same thing will be repeated for sample2 and then after that is finished, the global execution context will be destroyed.
It all happening like create context, code execution context, and deletion context with the help of call stack
There are various names for Callstack
- Program stack
- Runtime stack
- Machine Stack
Execution context stack.
Reference Akshay Saini from namaste javascript