``Everything in JavaScript happens inside an execution context.
That means whenever any JS program is run the Call Stack is populated with the global execution context and when a function is invoked a new execution context is created, after the execution of the function the command will back to the global execution context and the execution context will be pop out of the Call Stack.
Call Stack
Call stack is used for managing Execution Context. Whenever an Execution Context is created it is pushed into the stack and whenever an Execution Context is deleted it will move out of the stack.
"Call Stack maintains the order of execution of Execution Contexts"
What is Execution Context?
Execution Context comprises two components.
- The first component is known as the memory creation or variable environment. It stores all the variables and functions as key-value pairs.
- The second component is code execution or Thread of execution. In This code is executed line by line.
JavaScript is a synchronous single-threaded language.
`
var n = 2;
function square(num) {
var ans = num * num;
return ans;
}
var square2 = square(n)
var square4 = square(n)
`
As soon as we run the above program a global execution context is created and pushed into the Call Stack.
Phase 1: In the memory creation phase we allocate memory to all the variables and functions inside the global space where the variables stores with special value undefined and the function declaration or statement stores the whole body of the function.
Phase 2: Code execution phase, where JS code will execute line by line.
The value 2 will allocated to n and after that function square where nothing is there to execute. Then in square2, we invoke the square function with argument. So, a new execution will be created.
Whenever we invoke a function a new execution context is created.
The function return keyword states that, now return the program control where this function was invoked or called.
As soon as we return a value from a function or execute a function, the instance of that function will be deleted from the execution context. after allocating the value to the variable where it was invoked the execution context will also pop out from the call stack.
This is all about how JavaScript code is executed.
Top comments (0)