JavaScript Execution Context Cycle

JavaScript Execution Context Cycle

Introduction

The JavaScript execution context is a critical concept to understand how JavaScript code is parsed and executed. It is the environment where JavaScript code is evaluated and executed. Understanding the execution context helps in comprehending the scope, hoisting, closures, and execution order in JavaScript.

Types of Execution Contexts

Global Execution Context (GEC)

The Global Execution Context is the default context where code that is not inside any function is executed. When a JavaScript file is loaded into a browser, the JavaScript engine creates a global execution context.

  • Global Object: In a browser environment, this is the window object. In Node.js, it is the global object.
  • this Keyword: In the global context, this refers to the global object.
  • Uniqueness: There is only one global execution context in a JavaScript program.

Function Execution Context (FEC)

A new Function Execution Context is created each time a function is called. Each function has its own context, which is created and destroyed dynamically as the function is invoked and returns:

  • Local Variables: Each function context has its own local variables.
  • Function Scope: It also includes the arguments object and any variables declared within the function.
  • this Keyword: Inside a function, this can refer to different objects depending on how the function is called.

Eval Execution

Context An Eval Execution Context is created when the eval() function is executed:

  • Local Scope: Code executed inside eval() has access to the local scope in which eval() is called.
  • Usage: Rarely used due to security and performance issues.

Phases of Execution Context

The creation of an Execution Context (GEC or FEC) happens in two phases:

  1. Creation Phase
  2. Execution Phase

Creation Phase

During the creation phase, several important tasks are performed before the code execution begins:

  • Global Object Creation: The global object is created.
  • ‘this’ Binding: ‘this’ is bound to the global object in the global context or to the calling object in a function context.
  • Lexical Environment: A lexical environment is created, which includes the environment record (storing variables, function declarations, and ‘this’ binding) and a reference to the outer environment.
  • Scope Chain: The scope chain is set up to provide access to variables and functions in the current scope and its parent scopes. The scope chain is a list of objects representing the variables accessible at different levels of nested scopes.
  • Hoisting: Variable and function declarations are moved to the top of their scope. Variables declared with ‘var’ are initialized to ‘undefined’, while function declarations are hoisted with their definitions. Example code:

1.	console.log(foo); // undefined
2.	var foo = "Hello";
3.	
4.	bar(); // "Hello"
5.	function bar() {
6.	    console.log("Hello");
7.	}        

Execution Phase

In the execution phase, the code within the execution context is executed line by line:

  • Code Execution: The JavaScript engine executes the code, resolving variables and executing functions.
  • Variable Assignment: Variables are assigned their values.
  • Function Invocation: Functions are called, and new execution contexts are created and pushed onto the stack. 

Execution Stack (Call Stack)

The Execution Stack, also known as the Call Stack, keeps track of all the Execution Contexts created during the life cycle of a script.

JavaScript is a single-threaded language, which means that it is capable of only executing a single task at a time. Thus, when other actions, functions, and events occur, an Execution Context is created for each of these events. Due to the single-threaded nature of JavaScript, a stack of piled-up execution contexts to be executed is created, known as the Execution Stack.

When scripts load in the browser, the Global context is created as the default context where the JS engine starts executing code and is placed at the bottom of the execution stack.

The JS engine then searches for function calls in the code. For each function call, a new FEC is created for that function and is placed on top of the currently executing Execution Context.

The Execution Context at the top of the Execution stack becomes the active Execution Context, and will always get executed first by the JS engine.

As soon as the execution of all the code within the active Execution Context is done, the JS engine pops out that particular function's Execution Context of the execution stack, moves towards the next below it, and so on. The approach is also known as LIFO(Last in first out).

Article content
Call Stack (LIFO order)


Example:

1.	var a = 10;
2.	
3.	function foo() {
4.	    var b = 20;
5.	    function bar() {
6.	        var c = 30;
7.	        console.log(a, b, c);
8.	    }
9.	    bar();
10.	}
11.	
12.	foo();        

Execution Cycle Breakdown:

  1. Global Execution Context Creation Phase: Global object created. ‘this’ is set to the global object. ‘a’ is hoisted and initialized to ‘undefined’. ‘foo’ is hoisted and initialized to the function definition.
  2. Global Execution Context Execution Phase: ‘a’ is assigned the value ‘10’. ‘foo’ function is called, creating a new function execution context.
  3. Function Execution Context for foo Creation Phase: ‘b’ is hoisted and initialized to ‘undefined’. ‘bar’ is hoisted and initialized to the function definition.
  4. Function Execution Context for foo Execution Phase: ‘b’ is assigned the value ‘20’. ‘bar’ function is called, creating a new function execution context.
  5. Function Execution Context for bar Creation Phase: ‘c’ is hoisted and initialized to ‘undefined’.
  6. Function Execution Context for bar Execution Phase: ‘c’ is assigned the value ‘30’. ‘console.log(a, b, c)’ is executed, printing ‘10, 20, 30’.


To view or add a comment, sign in

More articles by Md. Nahid Hasan

  • 🚀 6 ChatGPT Prompts to Supercharge Your Productivity 🚀

    🔍 Struggling to write effective AI prompts? These six powerful shortcuts will help you get the most out of ChatGPT…

  • Soft drinks in Bangladesh

    In Bangladesh, there are a wide variety of soft drinks available for consumers to choose from. These include both…

    2 Comments

Explore content categories