Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How does JavaScript work behind the scene?
JavaScript is a powerful language that has revolutionized frontend development. Understanding how JavaScript works behind the scenes is crucial for writing efficient code and debugging effectively.
JavaScript is a synchronous, single-threaded language that executes code in a specific order. Everything in JavaScript runs inside an Execution Context, which is the environment where code is executed.
What is an Execution Context?
The Execution Context consists of two main components:
-
Memory Component (Variable Environment) - Stores variables and functions as key-value pairs
-
Code Component (Thread of Execution) - Executes code line by line
How JavaScript Execution Works
JavaScript execution happens in two phases:
- Creation Phase - Memory is allocated for variables and functions
- Execution Phase - Code is executed line by line
Example: Step-by-Step Execution
Let's trace through a simple JavaScript program to understand the execution process:
var m = 3;
var n = 2;
function sum(num1, num2) {
var ans = num1 + num2;
return ans;
}
var sumOfNos = sum(m, n);
console.log(sumOfNos);
5
Phase 1: Memory Creation
During the creation phase, JavaScript allocates memory for all variables and functions. Initially, all variables are set to undefined, while functions are stored completely in memory.
Phase 2: Code Execution
In the execution phase, JavaScript runs the code line by line, assigning actual values to variables and executing function calls.
Function Call Execution
When sum(m, n) is called, a new execution context is created for the function with its own memory and code components.
// When sum(3, 2) is called, a new execution context is created
function sum(num1, num2) {
// Memory: num1 = 3, num2 = 2, ans = undefined (initially)
var ans = num1 + num2; // ans = 5
return ans; // Returns 5 to the calling context
}
Key Points
JavaScript creates a Global Execution Context when the program starts
Each function call creates a new Function Execution Context
Variables are hoisted and initially set to
undefinedFunctions are completely stored in memory during the creation phase
The Call Stack manages multiple execution contexts
Conclusion
Understanding JavaScript's execution model helps you write better code and debug issues more effectively. The two-phase execution process?memory creation followed by code execution?is fundamental to how JavaScript operates behind the scenes.
