Skip to main content

Command Palette

Search for a command to run...

JavaScript Execution Context

Updated
5 min readView as Markdown
JavaScript Execution Context
T
Currently, I'm working as an AI Intern in the healthcare industry, where I am building Mobile application and retrieval-augmented generation (RAG) systems I use Node.js and Express.js to build backend services and React Native for frontend development.

In the previous blog, I discusses on the whether JavaScript is compiled or interpreted language. Here is the link: https://learnwithtaha.hashnode.dev/is-javascript-compiled-or-interpreted

In this blog, I will be sharing my recent learning on JavaScript Execution Context which gives me clear understanding how JavaScript works behind the scenes. We often write code and run it but lacks under the hood working of it.

At the end of the blog, you will understand:

  1. What is Engine and Host Environment

  2. What is Execution Context

  3. What is Global and Function Execution context

  4. Two types of phases: Memory allocation phase, Execution phase

  5. What is Call Stack

Introduction to Engine and Host environment

JavaScript Execution requires cooperation of two components:

  1. JS Engine

  2. Host Environment

JavaScript Engine provides core functionality. It takes source code, parses it and executes it. But in order to interact with the outside world, such as to produce any meaningful output, to interface with external resources we need mechanism that is provided by Host environment.

Example of Engines:

  1. Chrome & Node.js uses V8 Engine

  2. Firefox uses SpiderMonkey

  3. Safari uses JavaScriptCore

Example of Host Environment

  1. Browser like Google Chrome provides DOM, browser APIs

  2. Node.js provides File system, HTTP server


Understanding Execution Context

When JS engine scans a script file, it makes an environment called Execution Context. It act as an abstract concept and treated as a container that hold all the information about the environment within which the current JS code is being executed.

There are two types of Execution contexts: Global and Function.

Global Execution context is created when a JS script first starts to run and it represent global scope

Function Execution context is created whenever a function is called, representing the function's local scope.

There are two phases of JS Execution Context

  1. Memory Allocation Phase: In this phase, memory is allocated for all variables. All the functions and variables of code get stored as key-value pair inside memory. For function, JS copied the whole function into the memory block but in the case of variables, it assigned undefined as a placeholder.

  2. Execution phase: In this phase, engine executes the code in the execution context. It processes statements or expressions and evaluate if any function calls.


    Example

let val1=10;
let val2=5;

function addNum(num1,num2){
    let total=num1+num2;
    return total;
}

let result=addNum(val1,val2);

At the very beginning, JS engine executes the entire source code and creates a global execution context and does the following things:

  1. Creates a global object that is Window in the browser and global in Node.js

  2. Sets up a memory for storing variables and functions.

  3. Stores the variable with values as undefined and function references.

Refer the given below diagram

Once the memory allocation phase is completed, the next step is Execution phase.

In this phase, Engine assigns value to val1 and val2. Since addNum is a function, engine creates function execution context that contains new variable environment and execution thread.

This newly created function execution has again two phases

  1. Memory Creation Phase: In this phase, the variable inside the function is assigned with memory. Memory is allocated to variables num1 num2 and total

  2. Execution phase: In this phase, the variables is assigned with the values and addition statement is executed. The total after summation is returned to result global context. Once the total is returned, this function execution context get deleted.


Call Stack

JS Engine is a single threaded interpreter comprising

  1. Heap

  2. Single call stack

Call stack is primarily used for function invocation (call). It work on the principle LIFO (Last In First Out) to temporarily store and manage function call. Here since it is single threaded, code execution is synchronous.


function firstFunction(){
  console.log("Hello from firstFunction");
}

function secondFunction(){
  firstFunction();
  console.log("The end from secondFunction");
}

function thirdFunction(){
  secondFunction();
  console.log("The end from thirdFunction")
}

thirdFunction();
  • When thirdFunction() get executed, an empty stack frame is created. It is the entry point of the program.

  • thirdFunction() then calls secondFunction() which is pushed into the stack.

  • secondFunction() then calls firstFunction() which is pushed into the stack.

  • firstFunction() returns and prints Hello from firstFunction

  • firstFunction() is pop off the stack.

  • The execution order then move to secondFunction() and prints The end from secondFunction and pop off the stack

  • The execution order then move to thirdFunction() and prints The end from thirdFunction

  • The thirdFunction() is pop off the stack, clearing the memory

Output:

Hello from firstFunction
The end from secondFunction
The end from thirdFunction

Conclusion

JS Execution context is crucial to determine environment in which code is executed and what variables and functions are available to use.

The creation phase includes creating global and function execution context creating the scope chain, allocating memories for variables and functions. During execution phase, JS Engine executes the code line by line. It includes evaluating and executing statements.

Thanks for reading my blog!! Hope it helped you

If you want more sample code for all the concepts in JavaScript, do visit my GitHub Repo: GitHub Repo

You can connect with me on LinkedIn: LinkedIn


References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model

  2. https://www.geeksforgeeks.org/javascript/javascript-code-execution/

  3. https://www.freecodecamp.org/news/global-execution-context-and-temporal-dead-zone-explained/

  4. https://www.youtube.com/watch?v=ByhtOgF6uYM&pp=ygUdY2hhaSBhdXIganMgRXhlY3V0aW9uIGNvbnRleHQ%3D

  5. https://www.youtube.com/watch?v=ZvbzSrg0afE&pp=ygUeYWtzaGF5IHNhaW5pIGV4ZWN1dGlvbiBjb250ZXh0

  6. https://www.freecodecamp.org/news/understanding-the-javascript-call-stack-861e41ae61d4/

  7. https://developer.mozilla.org/en-US/docs/Glossary/Call_stack