Understanding JavaScript Execution Context

Arindam Majumder - Oct 3 '23 - - Dev Community

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 "Javascript Execution context."

💡
Each browser has its own version of the JavaScript engine. Chrome uses V8 Engine, Firefox uses SpiderMonkey, and Safari uses JavaScriptCore.

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.

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

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.

💡
Note: For every JavaScript file, there can only be one GEC.

Let's understand this with examples,

First Example:

First, Create a Demo HTML file,

<html> 
    <head> 
        <script src="index.js" />
    </head> 
    <body>Hello! I'm Arindam </body>
</html>
Enter fullscreen mode Exit fullscreen mode

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

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

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.

Let's understand with another example,

Second Example:

var name = 'Ronaldo'; 
function sayName() { 
    console.log(this.name); // Ronaldo
}
Enter fullscreen mode Exit fullscreen mode

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.

💡
Note: For each of the function invocations, there will be a Function Execution Context created

Let's understand this with an example,

function greet(name) {
  var message = "Hello, " + name;
  console.log(message);
}
greet("Aritree"); // Output: "Hello, Aritree"
Enter fullscreen mode Exit fullscreen mode

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 and explore the various sponsorship options.

Connect with me on Twitter, LinkedIn, Youtube and GitHub.

Thank you for Reading :)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player