JavaScript Execution Context and Code Execution with Examples

Gauri RautGauri Raut
4 min read

JavaScript is a single-threaded language, which means that it can only execute one line of code at a time. However, JavaScript can use a technique called call stacking to execute multiple functions at the same time. In this blog, we will explore execution context, code execution and call stacks in JavaScript.

What is the Execution Context?

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.
During the context runtime, the parser parses the source code and allocates memory for the variables and functions. The source code is generated and gets executed.

There are two main types of execution contexts in JavaScript: global execution context and function execution context

Global Execution Context:

  • The global execution context is the initial environment in which your code starts running.

  • It contains global variables and functions that are accessible throughout your entire program.

  • The global context also includes the global object (e.g., window in a web browser) and the this keyword, which refers to the global object.

Function Execution Context:

  • Each time a function is called, a new function execution context is created.

  • Inside this context, local variables and function parameters are declared and defined, and they are only accessible within that function.

  • Function contexts can also access variables from their outer contexts, forming a scope chain that allows functions to access variables from their parent scopes.

Code Execution in JavaScript:

Let's break down how JavaScript executes your code with a practical example:

// Global variable
let globalVar = "I'm global!";
function greet(name) {
    // Local variable
    let greeting = "Hello, ";
    console.log(greeting + name + "!");
}
greet("Alice");

This execution context is created in two phases:

Creation Phase:

  • During this phase, JavaScript sets up execution contexts. It hoists variable and function declarations.

  • Memory space is allocated for variables and functions. In the example above, globalVar, greet, and name are registered.

  • JavaScript now knows about all the variables and functions in the context.

  • When it allocates memory to the variables, it stores a special value undefined. For functions, it stores the whole function body inside this memory space.

Execution Phase:

  • In the execution phase, the actual code is executed line by line.

  • Variables are assigned values, and functions are invoked.

  • The order of execution follows the scope chain, moving from inner to outer contexts.

In the example, we first enter the global execution context. Then, when greet("Alice") is called, a new function execution context is created.

Execution Context Example:

// Global context
// Execution Phase
// Register globalVar
// Register greet function
// Execute greet("Alice")
// Create function execution context for greet

// Function execution context (for greet)
// Register greeting variable
// Register name parameter
// Execute console.log

This simple example illustrates the creation and execution phases of execution contexts in JavaScript.

Call Stack:

A call stack is a stack of execution contexts. When a function is called, a new execution context is pushed onto the call stack. When a function returns, its execution context is popped off of the call stack.

The following visual example shows how execution contexts, code execution, and the call stack work together:

// Global execution context
console.log("Global");
function foo() {
  console.log("foo");
}
function bar() {
  foo();
  console.log("bar");
}
bar();

When the code above is executed, the following happens:

  1. The global execution context is created.

  2. The foo() function is called. A new execution context is created for foo().

  3. The code in foo() is executed. This logs "foo" to the console.

  4. The foo() function returns. The foo() execution context is popped off of the call stack.

  5. The bar() function continues executing. This logs "bar" to the console.

  6. The bar() function returns. The bar() execution context is popped off of the call stack.

The global execution context is now the only execution context left on the call stack.

In Simple Terms:

JavaScript manages your code like a chef following recipes. It sets up a global kitchen (execution context) and workstations for helpers (function execution contexts). The chef reads the recipes step by step, follows each recipe in the correct order, and completes one task at a time, just like a chef preparing orders from a stack.

Understanding these concepts is like becoming a better chef in the world of web development. It ensures your code follows the right recipes and serves delightful web experiences to your users.

0
Subscribe to my newsletter

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

Written by

Gauri Raut
Gauri Raut

I am a software engineer primarily working on C++. Interested in all aspects of software development, from design and architecture to implementation and testing. I'm also a big believer in continuous learning and improvement, currently learning web development as part of my interest in expanding my skill set.