DEV Community

Cover image for Behind the Scenes: JavaScript Code Execution
Shreya Joshi
Shreya Joshi

Posted on

Behind the Scenes: JavaScript Code Execution

Ever found yourself in a late-night coding session, staring at your JavaScript code and wondering,"What is going on here?" 🤷🏻‍♀️

Well, buckle up because we're about to take a ride through the execution context of JavaScript. Maybe not as exciting as binge-watching your favourite series, but trust me, it's important stuff 🤨! You might not know it, but there's a whole lot happening behind the scenes when you write a simple script.🤯

Let's break down what an execution context is and why it’s important to know how it works in JavaScript.

Execution Context: What is it?

All JavaScript code needs an environment to run in, and typically that environment is a web browser. The browser’s JavaScript engine sets up a special environment to manage your code, known as an Execution Context.
It's where all the action happens, as your code gets parsed, interpreted, and executed.
Image description
There are two types of execution contexts in JavaScript:

  1. Global Execution Context (GEC)
  2. Function Execution Context (FEC)

Global Execution Context (GEC)

When a JavaScript file is loaded, the engine first creates a default Execution Context called the Global Execution Context (GEC). It's the top-level environment where global variables and functions live.

Note: there can only be one per JavaScript file.

Function Execution Context (FEC)

Every time you call a function, the JavaScript engine creates a Function Execution Context (FEC). This FEC lives inside the GEC, and it runs the function's code.

Note: Since each function call creates its own FEC, you might end up with multiple FECs at runtime.

Call Stack: The Execution Organizer

The Call Stack, also known as the Execution Stack, plays a key role in JavaScript's execution model. It keeps track of all the Execution Contexts created during the life cycle of a script.

It follows a Last In, First Out (LIFO) structure, meaning the most recently called function is executed first and removed from the stack when it finishes.

This stack-based execution model allows JavaScript to manage function calls, returns, and the flow of control within a script.

Image description

Creation of Execution Contexts

Now, let's talk about how these execution contexts (GEC or FEC) are created.
It happens in two phases:

  1. Creation Phase
  2. Execution Phase

1️⃣ Creation Phase (Memory Phase)

In this phase, variables and functions are declared in memory but not yet initialized. The Execution Context Object holds important data for the code in the Execution Context during its run-time.

The creation phase includes 3 stages:

  1. Creation of the Variable Object (VO)
  2. Creation of the Scope Chain
  3. Setting the value of the this keyword

Creation Phase: Creation of the Variable Object (VO)

The Variable Object (VO) is an object-like container created within an Execution Context. It stores the variables and function declarations defined within that Execution Context in the Memory Component as shown below in the diagram

  • Variables declared with var are set to 'undefined' in the VO.
  • Function declarations are added to the VO and stored in memory, making them accessible even before the code starts running.

Image description

This process of storing variables and function declaration in memory prior to the execution of the code is known as Hoisting

Creation Phase: Creation of The Scope Chain

In FEC, Each Function Execution Context creates its scope: the space/environment where the variables and functions it defined can be accessed via a process called Scoping.

When a function is defined inside another function, the inner function can access the outer function's code and even the scope of its parent functions. This hierarchy of scopes is known as lexical scoping.

Image description

This concept of scope brings up an associate phenomenon in JavaScript called closures.

Creation Phase: Setting The Value of The "this" Keyword

The JavaScript **this** keyword refers to the scope where an Execution Context belongs.

  • In the Global Execution Context (GEC), the this keyword refers to the global object, which in a web browser is the window object.
  • In the Function Execution Context (FEC), the this keyword points to the context where the function is called. This depends on how the function is invoked.

These stages set the foundation for code execution in JavaScript by properly organizing the context's memory, scope, and references.

2️⃣ Execution Phase

_This is where the real work gets done. _
After the creation phase, the execution phase begins.Up until now, the VO contained variables set to undefined.

Now, the JavaScript engine reads the code again, updates the all the variable with the actual values, and then the code is executed.

Let's Put It All Together

To understand how this all plays out, consider the following example:

Image description

Here's how the execution context unfolds step by step in your JavaScript code:

➡️ Step 1: Global Execution Context (GEC)

Phase 1 : Memory Creation Phase:

  • var n = 5 declaration creates a variable n with an initial value of **undefined** .
  • function square(n) declaration creates the function square .
  • showsquare declaration creates a variable with an initial value of undefined.

Phase 2 : Execution Phase:

  • n assigned the value 5.
  • var square1 = square(n) is evaluated. This calls the function square with the argument n (which has a value of 5). The Call Stack is used to create a new Function Execution Context (FEC) for the square function.

➡️ Step 2: Function Execution Context (FEC)

Phase 1 : Memory Creation Phase:

  • In the square function, the parameter n is created and assigned the value of 5 (the argument passed in).
  • The variable ans is created and initialized to undefined.

Phase 2 : Execution Phase:

  • The expression n * n is calculated, resulting in 5 * 5 = 25.
  • The variable ans is assigned the value of 25.
  • The square function returns the value 25 and its Function Execution Context is popped off the Call Stack.

Image description

➡️ Step 3: Return to Global Execution Context

  • The returned value 25 from the square function is assigned to the showsquare variable in the Global Execution Context.
  • The console.log(showsquare) statement is executed, printing the value 25 to the console.

Image description

By following these steps, the JavaScript engine processes the code in terms of creating and executing the necessary execution contexts for both the global and function scopes.

And there you have it! By understanding how execution contexts work, you gain insight into how JavaScript processes your code.👩🏻‍💻

Thanks for Reading! 😃

Connect with Me! 🙋🏻‍♀️
If you enjoyed this journey through JavaScript execution contexts, be sure to check out my website for more tech insights. I am also on Instagram and LinkedIn for more updates.

And if you want to keep everything neat and tidy, Linktree might just be your new best friend.

Happy Coding! 🎉

Top comments (0)