All about Execution Context in JavaScript

All about Execution Context in JavaScript

Everything in JavaScript happens inside Execution Context. Simply, the Execution context is the container and it consists of different phases. They are the memory creation and code execution phases. Memory creation is handled by the memory component, while code execution is handled by the code component.

In this article, we will dive deep into both of the components.

let num = 2;
function square(n){
  return result = n*n;
}

let ans = square(num)
let res = square(3)

Let's take this example and see what happens behind the scene in JavaScript. Before knowing what happens, we need to learn about two components as I mentioned earlier.

Memory Component: The memory component is also called the Variable environment. In this component, variables and functions are stored in the form of key-value pair (a:10).

Code Component: The code component is also called the thread of execution. In this component, our written code is executed line by line.

Now, as the program executes the phase will run as the memory creation phase and in this phase, the variables num, ans, and res are initialized but their value will be undefined initially. Also, the function square will be initialized similarly as defined in the code. After that, the code execution phase takes place and the code will execute line by line and the value of the variables will change as per the code execution.

As the code executes, the num value will change to 2 but in the case of function square, there is no need to do anything as it had already been executed. So, it jumps to execute ans variable and it will invoke a square function with a num argument. While executing, the ans variable will re-create the execution context and when it returns the value after executing the function in the execution context the value of the ans variable in the memory component will be set as 4.

A similar process will return the value of the res variable to 9. So, the final result will be.