JavaScript - Execution Context



We will learn about the JavaScript execution context in this chapter, where we will also cover its types, definition, execution stack, creation process, and overall execution phase. We will go over each topic individually. First, let's get started with the introduction.

What is Execution Context?

The execution context is a term that describes the internal workings of code. The JavaScript Execution Context describes the environment in which JavaScript code can be run. The execution context specifies which code sections have access to the functions, variables and objects used in the code.

During the execution context, the given code is parsed line by line, with variables and functions kept in memory. An execution context is similar to a container for storing variables; code is evaluated and then executed. So, the execution context provides an environment in which specific code can be executed.

Types of Execution Context

The JavaScript execution context types are as follows −

  • Global Execution Context/GEC

  • Functional Execution Context/FEC

  • Eval Execution Context

Now let us discuss each type one by one in the below section −

Global Execution Context

GEC (Global Execution Context) is often referred to as the base or default execution. Any JavaScript code that does not occur in a function will be found in the global execution context. The word 'default execution context' refers to the fact that the code is executed when the file is first loaded into the web browser. GEC carries out the following two tasks −

  • First, it creates a global object for Node.js and a window object for browsers.

  • Second, use the keyword 'this' to refer to the Windows object.

  • Create a memory heap to store variable and function references.

  • Then it stores all function declarations in the memory heap and initializes all variables in the GEC with 'undefined'.

Because the JS engine is single-threaded, there is only one global environment that may be used to execute JavaScript code.

Functional Execution Context

FEC, or Functional Execution Code, is the type of context generated by the JavaScript engine when a function call is found. Because each function has its own execution context, the FEC, unlike the GEC, can have multiple instances. Also, the FEC has access to the whole GEC code, while the GEC does not have access to all of the FEC's code. During GEC code execution, a function call is initiated, and when the JS engine finds it, it generates a new FEC for that function.

Eval Function Execution Context

Any JavaScript code executed using the eval function creates and retains its own execution context. But JavaScript developers do not use the eval function which is a component of the Execution Context.

Phases of the Execution Context in JS

There are 2 main phases of JavaScript execution context −

  • Creation Phase: In the creation phase, the JavaScript engine establishes the execution context and configures the script's environment. It sets the values of variables and functions as well as the execution context's scope chain.

  • Execution Phase: In this phase, the JavaScript engine runs the code in the execution context. It parses any statements or expressions in the script and evaluates any function calls.

Everything in JavaScript works within this execution context. It is divided into two parts. One is memory and the other one is code. It is important to keep in mind that these phases and components are applicable to both global and functional execution settings.

Creation Phase

Let us see the below example −

var n = 6;

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

console.log(sqr1)
console.log(sqr2)

Output

This will generate the below result −

36
64

Initially, the JavaScript engine executes the full source code, creates a global execution context and then performs the following actions −

  • Creates a global object that is a window in the browser and global in Node.js.

  • Creates a memory for storing variables and functions.

  • Stores variables with undefined values and function references.

After the creation phase the execution context will be moved to the code execution phase.

Execution Phase

During this step, it begins running over the entire code line by line from top to bottom. When it finds n = 5, it assigns the value 5 to the memory variable 'n'. Initially, the value of 'n' was undefined by default.

Then we get to the 'square' function. Because the function has been allocated memory, it goes right to the line var square1 = square(n);. square() is then invoked, and JavaScript creates a new function execution context.

When the calculation is finished, it assigns the value of square to the previously undefined 'ans' variable. The function will return its value and the function execution context will be removed.

The value generated by square() will be assigned to square1. This also applies to square two. Once all of the code has been executed, the global context will look like this and will be erased.

Execution Stack

The JavaScript engine uses a call stack to keep track of all contexts, both global and functional. A call stack is also referred to as a Execution Context Stack, Runtime Stack or Machine Stack.

It follows the LIFO concept (Last-In-First-Out). When the engine initially starts processing the script, it generates a global context and pushes it to the stack. When a function is invoked, the JS engine constructs a function stack context, moves it to the top of the call stack and begins executing it.

When the current function completes the JavaScript engine removes the context from the call stack and returns it to its parent. Let us check the below example code −

function firstFunc(m,n) {
   return m * n;
}
function secondFunc(m,n) {
   return firstFunc(m,n);
}
function getResult(num1, num2) {
   return secondFunc(num1, num2)
}
var res = getResult(6,7);
console.log("The result is:", res);

Output

This will produce the below result −

The result is: 42

In this case, the JS engine creates a global execution context and starts the creation process.

It initially allocates memory for firstFunc, secondFunc, the getResult function, and the res variable. Then it invokes getResult(), which is pushed to the call stack.

Then getResult() calls secondFunc(). At this point, secondFunc's context will be saved to the top of the stack. Then it will begin execution and invoke another function, firstFunc(). Similarly function A's context will be pushed.

After execution of each function it is removed from the call stack.

The call stack's size is determined by the operating system or browser. If the number of contexts exceeds the limit a stack overflow error will be returned. This happens when a recursive function has a base condition.

function display() {
   display();
}
display();

Output

This will generate the below result −

C:\Users\abc\Desktop\Javascript\example.js:2
    display();
    ^
RangeError: Maximum call stack size exceeded

Summary

Finally, understanding how JavaScript works behind the scenes needs knowledge of the execution context. It defines the environment in which code is executed as well as the variables and functions available for use.

The method of building involves creating the global and function execution contexts, the scope chain and allocating memory for the variables and functions. During the execution step the JavaScript engine goes over the code line by line. This includes evaluating and executing statements.

Advertisements