JavaScript Execution Context: A Deep Dive
Tags: javascript, webdev, discuss, tutorial
Published: 2023-03-09 17:46:57

## Real Life Example Of Execution Context

Suppose you're the manager of a restaurant, and your restaurant is like a JavaScript program. Each section of the restaurant represents an execution context.

The first section of the restaurant is the dining room, which is like the global execution context in JavaScript. This is the main area where the customers come to eat and enjoy their meals. It contains everything that's required for the restaurant to run smoothly, like the tables, chairs, menus, and waitstaff. This is similar to how the global execution context contains all the variables, functions, and objects that are needed for a JavaScript program to run.

Now, let's say a customer wants to order a meal. The customer is like the user input, and the act of taking their order is like creating a new execution context. The waiter takes the customer's order and moves to the kitchen area, which is like creating a new execution context in JavaScript.

In the kitchen area, the chef and kitchen staff prepare the meal based on the order taken by the waiter. This area is like a new execution context, similar to how each function call in JavaScript creates a new execution context. The kitchen has its own set of tools and ingredients, just like each execution context in JavaScript has its own set of variables and functions.

Once the meal is prepared, it's delivered to the customer in the dining room. This is like the result of a function call being returned to the global execution context. The customer receives their meal, and the restaurant continues to operate smoothly.

Overall, just like how a restaurant operates with different areas serving different functions, JavaScript code operates in different execution contexts as it moves through a program.


## JavaScript

JavaScript is a high-level programming language used for web development. It is single-threaded, meaning it can only execute one command at a time, and is interpreted, meaning it is not compiled before execution.

V8 is a high-performance JavaScript engine developed by Google and used in their Chrome browser, as well as other applications. It compiles JavaScript code to machine code, improving its performance.

JavaScript is primarily used for client-side scripting, meaning it runs on the user's web browser, and is used to create dynamic and interactive web pages. It is often used in conjunction with HTML and CSS.


## Execution Context

JavaScript Execution Context is the environment in which JavaScript code is executed. It contains information about the variables, functions, and objects that are available to the code being executed, as well as the scope chain and the value of the 'this' keyword.

An execution context has two phases: 

1. creation phase
2. execution phase


**Creation Phase:**
In this phase, the JavaScript engine sets up the environment for the code to be executed. During this phase, the JavaScript engine creates the following:

- **The Variable Object (VO):** The VO contains all the variables and functions that are defined in the current scope. This includes function arguments, function declarations, and variable declarations. The VO is used to resolve identifiers to their values during execution.
- **The Scope Chain:** The Scope Chain is a list of Variable Objects that are accessible in the current scope. Each Variable Object in the Scope Chain represents a higher level of scope.
- **The "this" keyword:** The "this" keyword is set to the value of the "this" object.


**Execution Phase:**
In this phase, the JavaScript engine executes the code line by line. The JavaScript engine reads the code and executes it one line at a time. This phase involves the following steps:

- **Assigning Values to Variables:** During the execution phase, the JavaScript engine assigns values to variables. If a variable is not initialized, it has the value of 'undefined'.
- **Executing Functions and Code Blocks:** The JavaScript engine executes functions and code blocks as it encounters them in the code. If a function is called, the engine creates a new execution context for that function and adds it to the call stack.
- **Managing the Call Stack:** The call stack is a data structure that keeps track of the functions that are being executed. When a function is called, its execution context is added to the top of the call stack. When the function returns, its execution context is removed from the stack.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ug00tvxbdkyhxbfbauu.png)


The two main components of an execution context in JavaScript are:

- **Memory Component:** This refers to the memory space that is allocated for the code and data components within the context. This includes variables, objects, arrays, and other data structures that are used or manipulated by the code. The memory component is also responsible for maintaining the scope chain, which is a list of variable objects that a function has access to, starting with its own variable object and continuing with the variable objects of its parent functions, all the way up to the global variable object.
- **Code Component:** This refers to the actual code that is being executed within the context. It includes any function and variable declarations, as well as any other instructions that make up the code. During the creation phase of the execution context, the JavaScript engine sets up memory space for all variables and function declarations through a process known as hoisting.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqc3ltiimyy4n74tw9wm.png)

Together, these two components enable the JavaScript engine to execute code and manage data within the program. Understanding how these components work is crucial for writing efficient and effective JavaScript code.


Let's take an example:

``` js
function greetings() {
  console.log("Welcome to the JS world!");
}

greetings();

var number1 = 10;
var number2 = 5;

function add(number1, number2) {
  return number1 + number2;
}

function addExtra(number1, number2) {
  var extra = 15;
  return number1 + number2 + extra;
}

var result1 = add(number1, number2);
var result2 = addExtra(number1, number2);

console.log(result1);
console.log(result2);
```

Initially call stack is empty 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgmi1qfu7u4msqxv67ly.png)


The JavaScript engine first runs the complete source code then does the following:

- Create a Global Execution Context(G.E.C) and push it to the call stack.
- Creates a global object window in the browser and global in the NodeJs.
- Stores the variables with values as undefined and function body references.


Push Global Execution Context into the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7orfpc44zov4pgo2nl5.png)


Memory Creation for the Global Execution Context

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y34f5qfyagrxbr7ahh6z.png)


After this memory creation phase, the execution context will move to the code execution phase.
The `greetings` function is called.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w3v54m2ynv6mg3g71wbp.png)


Create greetings Execution Context and push it to the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71z1mjpbzphztar4ergb.png)

Memory Creation and Code Execution of greetings Execution Context. Here The `greetings` function is called, so it executes and logs the string "Welcome to the JS world!" to the console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esbtxq1qh75ob55bz7o8.png)

Console

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebhli3oxr8kblk3gm86b.png)

pop greetings Execution Context from the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7orfpc44zov4pgo2nl5.png)


variable `number1` defined and assigned value 10

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6otp14482r2o5tv8awa.png)


variable `number2` defined and assigned value 5

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twmeyhwkhuq2tmofr20h.png)


A function `add` is called, which takes two parameters `number1 = 10` and `number2 = 5`. Inside the function, the two parameters are added together and the `result = 15` is returned.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ochbvddgtpn5eymw6bgy.png)

Create add Execution Context and push it to the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfqr13gg44bcsml6zavi.png)


Memory Creation and Code Execution of add Execution Context. Here returned the sum of `number1` and `number2`.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sdzelimnvg06piip1ecz.png)


variable `result1` defined and assigned the result of calling the `add`.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1d1ijba83d3l9674zsk3.png)


pop add Execution Context from the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7orfpc44zov4pgo2nl5.png)


A function `addExtra` is called, which takes two parameters `number1` and `number2`. Inside the function, a new variable `extra` is defined and assigned a value of 15. Then, the sum of `number1`, `number2`, and `extra` is returned.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2xuf8fgd9nsdc7nzs2hp.png)


Create addExtra Execution Context and push it to the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yja3gqpcrub20ya3dttp.png)


Memory Creation and Code Execution of addExtra Execution Context. Here `extra` is defined and assigned a value of 15 and returned the sum of `number1`, `number2` and `extra`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpmm0ld1vtf3n9qa7lur.png)


variable `result2` defined and assigned the result of calling the `addExtra`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlqat5zk8zcu5z45ppxa.png)


pop addExtra Execution Context from the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7orfpc44zov4pgo2nl5.png)


The value of `result1 = 15` logged to the console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7k563z5m2obd2321hc3.png)

Console

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ahwkc7auryxaao7bhot.png)


The value of `result2 = 30` logged to the console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0irupf3oamygq5paa7f.png)


Console

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fwn6n17uujysmnz58ig6.png)


pop Global Execution Context from the call stack.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgmi1qfu7u4msqxv67ly.png)


## Conclusion

JavaScript execution context is a fundamental concept that defines the environment in which JavaScript code is executed. It plays a vital role in how JavaScript functions and interacts with its surrounding environment, and understanding it is essential to write efficient and effective JavaScript code. An execution context is a data structure that contains information about the environment in which the JavaScript code is executed.

Each execution context has a scope chain that determines what variables and functions the context has access to. The scope chain is determined by the lexical environment of the execution context and is used to look up variables and functions when code is executed.

The variable object is another important component of an execution context. It is a data structure that contains information about the variables, functions, and parameters defined in the execution context. The variable object is used to store and manage the variables and functions in the context and is updated dynamically as the code is executed.

The this keyword is also an important part of the execution context. The value of this is determined by the context in which a function is called. In the global execution context, this refers to the global object. In a function execution context, this refers to the object that the function is a method of, or the global object if the function is not a method of any object.

Hoisting is another concept that is closely related to execution context. In JavaScript, variable and function declarations are hoisted to the top of their respective execution contexts. This means that they can be used before they are declared in the code.

Finally, the execution stack is a data structure that stores execution contexts in a last-in, first-out (LIFO) order. When a function is called, a new execution context is created and pushed onto the top of the stack. When a function returns, its execution context is popped off the stack.

The execution context is a fundamental concept in JavaScript that defines the environment in which code is executed. It contains information about the variables, functions, and parameters defined in that environment, as well as the scope chain and the this keyword. By understanding the execution context, developers can write more efficient and effective JavaScript code, ultimately leading to better performance and more reliable applications.