JavaScript Execution Context

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:
What is Engine and Host Environment
What is Execution Context
What is Global and Function Execution context
Two types of phases: Memory allocation phase, Execution phase
What is Call Stack
Introduction to Engine and Host environment
JavaScript Execution requires cooperation of two components:
JS Engine
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:
Chrome & Node.js uses V8 Engine
Firefox uses SpiderMonkey
Safari uses JavaScriptCore
Example of Host Environment
Browser like Google Chrome provides DOM, browser APIs
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
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.
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:
Creates a global object that is Window in the browser and global in Node.js
Sets up a memory for storing variables and functions.
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
Memory Creation Phase: In this phase, the variable inside the function is assigned with memory. Memory is allocated to variables
num1num2andtotalExecution phase: In this phase, the variables is assigned with the values and addition statement is executed. The
totalafter summation is returned toresultglobal context. Once thetotalis returned, this function execution context get deleted.
Call Stack
JS Engine is a single threaded interpreter comprising
Heap
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 callssecondFunction()which is pushed into the stack.secondFunction()then callsfirstFunction()which is pushed into the stack.firstFunction()returns and printsHello from firstFunctionfirstFunction()is pop off the stack.The execution order then move to
secondFunction()and printsThe end from secondFunctionand pop off the stackThe execution order then move to
thirdFunction()and printsThe end from thirdFunctionThe 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
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model
https://www.geeksforgeeks.org/javascript/javascript-code-execution/
https://www.freecodecamp.org/news/global-execution-context-and-temporal-dead-zone-explained/
https://www.youtube.com/watch?v=ByhtOgF6uYM&pp=ygUdY2hhaSBhdXIganMgRXhlY3V0aW9uIGNvbnRleHQ%3D
https://www.youtube.com/watch?v=ZvbzSrg0afE&pp=ygUeYWtzaGF5IHNhaW5pIGV4ZWN1dGlvbiBjb250ZXh0
https://www.freecodecamp.org/news/understanding-the-javascript-call-stack-861e41ae61d4/
https://developer.mozilla.org/en-US/docs/Glossary/Call_stack

