Top JavaScript Interview Questions You Should Know

Suraj ChoudharySuraj Choudhary
2 min read

1. What is the Execution Context?

  1. When the JavaScript engine scans a script file, it makes an environment called the Execution Context that handles the entire transformation and execution of the code.

  2. Every Thing in JavaScript happens inside the "execution context".

  3. Execution context is like a big box where all the javascript executes.

Execution Context has 2 phases.

  1. Creation Phase: In the creation phase, the JavaScript engine creates the execution context.

  2. Execution Phase: Inside the execution phase, the JavaScript engine executes the code in the execution context.

Execution Context

Understand with a simple example:

var n = 5;

function square(n) {
  var ans = n * n;
  return ans;
}

var square1 = square(n);
var square2 = square(8);  

console.log(square1)
console.log(square2)

Now JavaScript engine will execute the entire source code and, create a global execution context.

  1. Creates a global object that is window in the browser and global in NodeJs.

  2. Sets up a memory for storing variables and functions.

  3. Stores the variables with values as undefined and function references.

This above phase is called the creation phase now see the diagram to understand.

Creation Phase in Execution Context

After the creation phase, the execution context will move to the code execution phase.

Execution Phase:

  • Now, in this phase, it starts going through the entire code line by line from top to bottom.

  • As soon as it encounters n = 5, it assigns the value 5 to 'n' in memory. Until now, the value of 'n' was undefined by default.

  • Then we get to the 'square' function. As the function has been allocated in memory, it directly jumps into the line var square1 = square(n);. square() will be invoked and JavaScript once again will create a new function execution context.

0
Subscribe to my newsletter

Read articles from Suraj Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suraj Choudhary
Suraj Choudhary

Who is a highly motivated and results-oriented Software Engineer with a passion for crafting robust and user-friendly web applications. Possesses strong expertise in both backend development and full-stack development, leveraging a diverse skillset to design, develop, and deploy scalable software solutions.