Execution Context
JavaScript engine and host environments
JavaScript code runs through a teamwork of two components:
JavaScript Engine (e.g., V8, SpiderMonkey):
Reads and executes your code line by line.
Manages memory, optimizations, and core language features.
Host Environment (e.g., HTML DOM in web Browser , Node.js):
Provides APIs (like
fetch
,document
,fs
) that JS can use.Handles external interactions (e.g., network requests, file system).
Execution Context
When JavaScript runs code, it first creates a special space called the Execution Context. This is where the code actually runs and does its work.
The Agent Execution Model in JavaScript
In JavaScript's execution architecture, each agent acts as an independent runtime environment with three key components:
1. Execution Stack (Call Stack) A Last-In-First-Out (LIFO) structure that keeps track of active execution contexts, such as function calls. Execution contexts are created by the JavaScript engine and pushed onto the stack when a function is invoked, and popped off when execution completes. JavaScript processes one execution context at a time in a single-threaded manner.
2. Job Queue (Event Loop)
A First-In-First-Out (FIFO) queue that handles asynchronous tasks (e.g., setTimeout
, Promise
callbacks). The event loop coordinates between the call stack and job queue to ensure non-blocking execution by scheduling queued tasks only when the stack is empty.
3. Object Heap
A memory area where objects, functions, and reference types are stored.
Each agent has its own heap. However, when using SharedArrayBuffer
, underlying memory regions can be shared between agents, allowing concurrent access — which may lead to race conditions if not properly synchronized.
Execution Context Types:
Global:
When it is created? When a JavaScript program starts running.
What it does? It sets up the global scope (the main area where variables and functions live).
In a browser, the global context creates the
window
object (which stores global variables and functions). In Nodejsglobal
is likewindow
in the browser.
Functional
When is it created? Every time a function is called.
What does it do? It creates a local scope for that function (variables and parameters inside the function stay separate from the global scope).
How long does it last? Only while the function is running. After the function finishes, it disappears.
Execution Phases:
The Setup Phase
Code Scanning:
The engine parses your script (like a hacker recon an asset).
It identifies all variables, functions, and lexical scopes.
Memory Allocation:
Variables: All variable are hoisted. I’ll get into this further down.
Functions: Entire declarations are loaded into memory
Scope Chains: Nested access hierarchies are locked in
The Execution Phase
Now, the code runs line by line. Variables get their values, and functions are executed. Finally, the program finishes its work (with either the correct result or errors
Last updated