Javascript execution context

Chandan KumarChandan Kumar
8 min read

Table of contents

Introduction

Why execution context important πŸ€”πŸ€”

JavaScript execution context might sound like a fancy term, but it's one of the most important concepts in JavaScript. It helps you develop a proper understanding of JavaScript and how it works. If you're interested in delving deeper into JavaScript, understanding execution context is essential. It creates a strong foundation in JavaScript, enabling you to write code more effectively and truly understand how things work under the hood.

Developers often encounter bugs in JavaScript and spend considerable time trying to identify the root cause. Understanding execution context provides insight into how operations are carried out and how the code functions, making it easier to diagnose and fix issues

Definition :- πŸ₯ΈπŸ₯Έ

JavaScript execution context is an environment in which JavaScript code runs. You can think of the execution context as a hotel where people (code) come, and each person is assigned a room (memory). They execute their tasks and then leave.In this some important components include like

Components in execution context πŸ”§πŸ”§

  1. Phases of execution context

  2. Global execution context

  3. Functions execution context

  4. hoisting in let , var , const

  5. Temporal dead zone

βœ…οΈ Types of execution context :- πŸ€”πŸ€”

In JavaScript there are two type of execution context:-

βœ…οΈ Global execution context :- πŸ–₯πŸ–₯

The global execution context is the default execution context in which JavaScript code runs.

It is created when the JavaScript engine starts executing a script and is responsible for setting up the global environment.

A real-life analogy 🌳 🌳

For the global execution context is a theater stage where a play is performed.

The stage represents the global environment, the actors are the variables and functions, and the script is the code being executed.

Just as the stage provides the setting for the play, the global execution context provides the environment for the code to run.

βœ…οΈ Global execution context have 2 phase:- 🌎 🌎

βœ…οΈ Creation phase :- 🌌🌌

The Creation phase in the execution context is a stage where. memory is allocated for all variables and functions. If the JavaScript code contains global variables, memory is allocated to them, and the entire body of functions is also loaded into memory.

But there are few things we have to take care about.

  1. var Variables: During the Creation phase, memory is allocated for variables declared with var, and they are initialized with undefined.

  2. let Variables: Memory is allocated for variables declared with let, but they are not initialized. They remain in a "temporal dead zone" until they are initialized in the code.

  3. const Variables: Similar to let, memory is allocated for const variables, but they are not initialized until the code assigns them a value. However, const variables must be initialized at the time of declaration.

  4. Functions: The entire body of function declarations is loaded into memory, allowing them to be invoked before their actual declaration in the code.

Example code πŸ§ͺπŸ§ͺ

Here we talk about what happens when we try access the
variable (let,const,var) before initialized 

///////////////////////////////////////////////////////////////
var firstVariable; //////////// CODE 1

function callFunctionOne(firstVariable) {
    Console.log(" hello number ", firstVariable) ;
}

callFunctionOne(firstVariable)

Result:- hello number undefined 

//////////////////////////////////////////////////////////////
let firstVariable;  ///////////////// CODE 2

function callFunctionTwo(firstVariable){
     Console.log("hello 🌎 ",  firstVariable)
}

callFunctionTwo(firstVariable)

Result:- reference error 

///////////////////////////////////////////////////////////////
Const firstVariable;  /////////////// CODE 3

function callFunctionThree(firstVariable){
Console.log("hello πŸ‰")
}

callFunctionThree(firstVariable)

Result:- reference error

βœ…οΈ In the Creation phase for variables declared with `var`, the following steps occur:

  • The variable is declared using the var keyword.

  • The JavaScript engine begins executing the code and creates a global execution context.

  • The global execution context has two phases:

    • In the creation phase for variables declared with var:

      • The global object is created, which is the window object in a browser environment.
  • The this keyword is created and refers to the global object.

  • The expression window === this holds true, meaning the this keyword is assigned to the global object.

  • Memory is allocated for all variables, whether declared with var, let, or const.

    βœ…οΈ In the creation phase for variables declared with let and const:

    • The variable is declared but not initialized.

    • Memory is allocated for the variable.

    • The variable is placed in a "temporal dead zone" until it is initialized.

    • Accessing the variable before initialization results in a ReferenceError. phase in let , const :-

☎️☎️ Note :- if we try to access the let , const before initialize it give reference error In let and syntax error in const because const must me Declared and initialize at the same time .

βœ…οΈ Execution Phase

In the execution phase, the JavaScript engine starts executing code line by line after the creation phase.

  • It assigns values to their respective variables and begins executing functions.

  • The following tasks are performed in this phase:

    1. All variables outside the function that are already initialized (var-declared variables) and other variables declared with let and const have their values assigned to them.

    2. If the code contains a function call, then for every function call, a new function execution context is created.

πŸ§ͺπŸ§ͺEXAMPLE

Here we learn who the execution phase proceed when the variable 
Have assigned value to it.

///////////////////////////////////////////////////////////////
var firstVariable = 10;/////////////// CODE 1

function callOne(firstVariable) {
   console.log (" hello one " , firstVariable);
}
callOne(firstVariable);

///////////////////////////////////////////////////////////////

let firstVariable = 3 ;////////////////CODE 2

function callTwo(firstVariable) {
   console.log(" hello two ", firstVariable);
}
callTwo(firstVariable);

///////////////////////////////////////////////////////////////

const firstVariable = 4 ; /////////////// CODE 3

function callThree(firstVariable) {
   console.log ("hello three", firstVariable);
}
callThree(firstVariable);

Here the the flow digram that help you to understand execution phase:-

βœ…οΈ Function execution contexts

βœ… Definition:

A Function Execution Context (FEC) is the environment that is created whenever a function is invoked. It contains everything the JavaScript engine needs to run that specific function properly.


πŸ” What it includes:

When a function is called, JavaScript creates a new execution context specific to that function. This context includes:

  1. Function Arguments – the values passed to the function.

  2. Local Variables – variables declared inside the function using var, let, or const.

  3. Scope Chain – access to outer variables (lexical environment).

  4. this Keyword – depends on how the function is called.

  5. Reference to the Outer Environment – link to the execution context where the function was defined.

πŸ§ͺ Example 1.

let last_name = "kumar";
function greet(name) {
  let message = "Hello, " + name + last_name;
  console.log(message);
      function inner(){
         let innerVar = 10;
         console.log("hello inner")
      }
       inner();
}

greet("Chandan", last_name);

🧭 Life Cycle of a Function Execution Context:

Creation Phase:

Creation phase here is the same as creation phase in global execution context . The only difference here is the instead of creatine global object (window) it creates arguments object and β€œthis” keyword bind to arguments object

βœ… In non-strict mode


function demo(a) {
 arguments[0] = 99 ;
 console.log(a); // a = 99
}
demo(1);

βœ… In non-strict mode the `arguments` object holds a reference to the parameters.

  1. So: `arguments[0] ↔ a` β€” they are linked.

  2. Changing one changes the other.

βœ…οΈIn strict mode

function demo(a) {
  arguments [0] = 99;
  console.log(a); // a = 10 value not change
}
demo(10);

In strict mode they are not linked.

  1. `arguments[0]` holds the value only.

  2. Changing `arguments[0]` does not affect `a`.

βœ…οΈ Execution Phase

During this phase:

1. βœ… Actual code inside the function runs** line by line.

2. βœ… Operations happen (like calculations, assignments, function calls).

3. βœ… Memory is used and released.

4. βœ… Return values. are sent back to the calling context.

❗ In Strict Mode:

  1. this keyword = `undefined`

  2. `arguments` does NOT sync with parameters

Take example of code 1

βœ…οΈ Common Mistakes:

βœ…οΈ Misunderstanding Hoisting:

Developers often assume that variables and functions are available before they are declared, leading to unexpected behavior.

βœ…οΈ Ignoring the Temporal Dead Zone:

Accessing `let` and `const` variables before they are initialized results in a ReferenceError, which can be confusing.

βœ…οΈ Incorrect `this` Binding:

Misusing the `this` keyword, especially in different contexts like event handlers or callbacks, can lead to bugs.

βœ…οΈ Overlooking Scope Chain:

Failing to understand how the scope chain works can result in accessing the wrong variables or functions.

βœ…οΈ Best Practices:

βœ…οΈ Use `let` and `const` Instead of `var`:

This helps avoid hoisting issues and makes the code more predictable.

βœ…οΈ Be Mindful of `this`:

Use arrow functions to maintain the lexical value of `this` or explicitly bind `this` when necessary.

βœ…οΈ Understand Execution Phases:

Familiarize yourself with the creation and execution phases to predict how and when variables and functions are available.

βœ…οΈ Leverage Strict Mode:

Use strict mode to catch common mistakes and enforce better coding practices.

πŸ§ͺπŸ§ͺConclusion

The execution context is a fundamental concept in JavaScript that influences how code is executed and variables are accessed. Understanding the global and function execution contexts, along with hoisting and the temporal dead zone, is crucial for writing efficient and bug-free code. By mastering these concepts, developers can enhance their JavaScript skills and write more robust applications.

πŸ“– πŸ“• Further Reading and Resources

Blogs ✍️ ✍️

  1. https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0

  2. https://www.javascripttutorial.net/javascript-execution-context/

  3. https://www.codu.co/articles/execution-context-in-javascript-c2ccp-4i

Video πŸ“ΉπŸ“Ή

  1. https://youtu.be/ylx5F7hbzVQ?si=rs2ye0OFevfwsXvp (tapaScript)

  2. https://youtu.be/gPKzwAORly8?si=_DEloaUwi8tWGS4k. (Piyush garg)

  3. https://youtu.be/JfW1fBRCeLU?si=s20-dudaPXDGvhDU. (Anurag Singh procoderr)

If you reach this far please share your feedback with me so can create blog in more effective and efficient way . πŸ™πŸ™πŸ™πŸ™

Thank you..😊😊😊

0
Subscribe to my newsletter

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

Written by

Chandan Kumar
Chandan Kumar

Tech enthusiast CSE student | Python, JS, Node.js, Web Dev | Learning DSA and exploring Web 3.0 πŸš€