Understanding JavaScript Execution Context
Tags: javascript, webdev, tutorial, beginners
Published: 2023-10-03 19:19:40

## Introduction

When we write JavaScript code, it's more than just lines of instructions. It creates a sequence of events and executes them in an order.

But, How does JavaScript decide the order in which these events are executed?

The answer is simple! With the help of Javascript Execution context.

In this article, we'll explore what it is, How it works, Lexical contexts and many more concepts! So Without delaying further, Let's Start!

## What is Executing Context?

Let's understand this from the word itself!

Execution = To execute the code,

Context = The Environment.

So, Execution Context is the *environment* where our *specific* code is *stored and executed.*

Didn't get it? No worries!

Now, Let's understand how the javascript code gets executed. Then the concept will be clear to you.

## How does Javascript code get Executed?

The Browser can't natively understand the javascript code we write in our application. So, To Make it understandable, the browser converts the javascript code into machine code.

Sounds interesting right?

Let's dive deep into it!

When we open a Web page, the browser requests the necessary files (mainly HTML, CSS & Javascript files) from the web server.

While reading through HTML, if the browser finds JavaScript code to run via a `<script>` tag or an attribute that contains JavaScript code like `onClick`, it sends it to its JavaScript engine.

Then the Browser's Javascript Engine creates a special environment to transform the javascript code into machine code. This environment is called <mark>"Javascript Execution context."</mark>

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Each browser has its own version of the JavaScript engine. Chrome uses <a target="_blank" rel="noopener noreferrer nofollow" href="https://v8.dev/" style="pointer-events: none">V8 Engine</a>, Firefox uses <a target="_blank" rel="noopener noreferrer nofollow" href="https://spidermonkey.dev/" style="pointer-events: none">SpiderMonkey</a>, and Safari uses <a target="_blank" rel="noopener noreferrer nofollow" href="https://trac.webkit.org/wiki/JavaScriptCore" style="pointer-events: none">JavaScriptCore</a>.</div>
</div>

After that, The JavaScript engine reads the code character by character, forms an Abstract Syntax Tree (AST), stores variables and functions in memory, and executes the code.

## Lexical Context :

Before understanding different types of execution contexts let's understand Lexical Context.

The word `Lexical` means **related to something**. Lexical Environment means how and where your code is physically placed.

```javascript
function outer() {
  const x = 10;
  function inner() {
    console.log(x); // 'x' is accessible here because of lexical context.
  }
  inner();
}
```

In this code snippet, the lexical context allows the `inner` function to access the variable `x` declared in its parent scope, `outer`.

Lexical context helps in creating the Abstract Syntax Tree (AST) and allows nested functions to work properly within their parent scopes.

## How are Execution Contexts Created?

Execution contexts are created in two phases.

* Creation Phase
    
* Execution Phase
    

## Types Execution Context:

There are two kinds of Execution Context in JavaScript:

* Global Execution Context (GEC)
    
* Function Execution Context (FEC)
    

### Global Execution Context:

Whenever we execute JavaScript code, it creates a Global Execution Context (also known as Base Execution Context). You can think of it as a container that contains other execution contexts.

It creates a global object (`window` object in case of browsers) and a global variable called `this`.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Note: For every JavaScript file, there can only be one GEC.</div>
</div>

Let's understand this with examples,

#### First Example:

First, Create a Demo HTML file,

```javascript
<html> 
	<head> 
		<script src="index.js" />
	</head> 
	<body>Hello! I'm Arindam </body>
</html>
```

Now run this simple code and open the Browser console. Then, Type `this` and see what happens.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690664546434/c2ef0bc2-823b-4c6e-96f4-b0a1679fd1b5.png)

We got a window object. Now, Type window and see what happens,

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690664726636/7f33fa72-c312-44be-9da7-595646f420bf.png)

Guess What? We got a window object again!

So, From this example, we understand that in the Global Execution Context, `this` and `window` object are the same.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690664966164/b26c8506-9540-4b31-9e0d-518c84d6f48a.png)

Let's understand with another example,

#### Second Example:

```javascript
var name = 'Ronaldo'; 
function sayName() { 
	console.log(this.name); // Ronaldo
}
```

Here, The code is executed in two phases,

In the Creation phase, Variables and functions are declared and initialized (memory allocated for the respective variables and functions). They are hoisted to the top of their scopes and create a global object `this` (window object in the case of the browser).

In the Execution phase, the code is executed sequentially. At first, the variable name is assigned to the value `Ronaldo` .Then the function `sayName()` executes and prints the output(here it's Ronaldo).

### Function Execution Context:

A Function Execution Context gets created when a function is called. It's created within the Global Execution Context. Inside the local execution context, the JS engine will create an `arguments` object and `this` object by default.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Note: For each of the function invocations, there will be a <strong>Function Execution Context</strong> created</div>
</div>

Let's understand this with an example,

```javascript
function greet(name) {
  var message = "Hello, " + name;
  console.log(message);
}
greet("Aritree"); // Output: "Hello, Aritree"
```

In this code, When the greet() function is called, it creates its execution context (FEC). Within the function scope, the same thing happens as GEC.

In the creation phase, It declares and initializes the variables and nested functions (if any).

In the execution phase, the variable name is assigned to the value passed through the function argument (Here it's Aritree). Then, The variable `message` is declared and initialized with the string `"Hello, Aritree"`. And then, it prints the value of the message.

## Conclusion:

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript and other web development topics.

To sponsor my work, please visit: [Arindam's Sponsor Page](https://arindam1729.hashnode.dev/sponsor) and explore the various sponsorship options.

Connect with me on [Twitter](https://twitter.com/intent/follow?screen_name=Arindam_1729), [LinkedIn](https://www.linkedin.com/in/arindam2004/), [Youtube](https://www.youtube.com/channel/@Arindam_1729) and [GitHub](https://github.com/Arindam200).

Thank you for Reading :)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690696967432/c331d64c-b5dc-44ff-b888-26ec14e51b97.png)