Execution Context in JavaScript
→ Everything in JavaScript happens inside an execution context.
→ The execution context has two components.
- Memory Component
- Code Component
→ All the functions and variables will be stored in the form of key-value pairs inside the memory component. The memory component is also known as Variable Environment.
→ The code component is the place where the code is executed one line at a time. Code component is also known as Thread of execution.
→ The execution phase is created in two phases.
- Memory Creation phase
- Code Execution phase
→ In memory creation phase, memory is allocated to the functions and variables and for variables the value will be initially set to undefined.
→ In code execution phase the value we gave for the variables will be replaced instead of undefined.
→ In code execution phase, for each function a brand new execution context will be created and it also has the memory and code components in it.
→ Again the variables and parameters inside the function are allocated memory and the value is set to undefined. In the code execution phase the code is executed line by line and the undefined will be replaced by the original values.
→ Finally when it reaches the return statement, the final answer is returned and the execution context of that particular function is permanently deleted from the Global Execution Context.
var n=2;
function square(num){
var answer = num*num;
return answer;
}
var sqaure2 = square(n);
var square4 = square(4);
The execution context of the above code is explained below.
The outer box (bigger table) is the global execution context. It has the memory and code component. In the global environment, variable “n” is first initialized with the special placeholder “undefined”. Function “square” is stored in a function like syntax.
In the code execution phase, the variable “n” is set to “2” instead of “undefined”. Once JavaScript encounters the function “square” another execution context is created it has its own memory and code components. The execution context is popped out of the call stack once the answer/value is returned by the function. Whenever a function is invoked, a brand new execution context is created.