Javascript is a synchronous and Single threaded language."Everything in Javascript happens inside the execution context".Execution context is like a big box that has two components Memory component and a code component which is also known as the Variable environment and Thread of execution respectively. Synchronous and single-threaded means that javascript will execute one command at a time in a specific order.
Eg:
var n=10;
function square(num){
var res=num*num;
return res;
}
var square10=square(n);
var square2=square(2);
output: 100
4
As we know Everything in javascript will be executed inside the execution context. when the program runs the global execution context is created which has two components Memory component(variable environment) and a code component(Thread of execution) in the variable environment the variables and functions are stored in the form of a key: value pair. In the first phase inside the global execution context memory is allocated to all the variables and functions and a default value "undefined" is assigned to the variables of the program functions will be assigned with the code inside them as it is in the program. The mechanism inside the javascript engine happens as follows:
After the memory allocation in the second phase, the program will execute line by line in the code execution phase. the value of variable n is assigned as "2" in the Global execution context. Then function code will be executed after the function is executed when the function is invoked in the program a new global execution context is created again it is divided into two components memory and code. The functions and variables will allocate memory and the code is executed inside the thread of execution. After returning the result the function will return the control to the global execution context and it will be deleted. After the code is completely executed the whole Global execution context is deleted. It becomes very complex for javascript to manage the global execution context, so to manage the whole mechanism Javascript has its call stack. whenever a global execution context is created it is pushed inside the call stack and when the task is completed it popped out of the stack. This is how the code inside the javascript engine will be executed.
Thanks for reading ๐ .
Memory | code | |
n: undefined | n=2 | |
function{........} | ans=num*num | |
num: undefined | return ans | |
ans: undefined | ||
square2: undefined | ||
square4: undefined |