DEV Community

Ivan Grekhov
Ivan Grekhov

Posted on

What Happens Before the Event Loop. Part 1

JavaScript code is not executed natively by an engine at the moment a task appears in the call stack. Most articles focus on how the Event Loop works, leaving out the path that developer-written instructions take before reaching that point. As a result, concepts such as scope, closures, the Temporal Dead Zone, and other execution details are often memorized as a kind of “technomagic”.

In this short series of posts, I want to break down these aspects by tracing the path from source code input to actual execution. To avoid diving too deeply into the implementation details of specific engines (V8, SpiderMonkey, JavaScriptCore, etc.), the discussion will stay at the abstraction level defined by the ECMAScript 262 specification.

Code Execution Stages

The specification intentionally does not describe JavaScript execution as a linear sequence of steps—implementation details are left to engine authors. Nevertheless, the spec (along with practical knowledge of engine implementations) allows us to identify four conditional stages:

  1. Determination of the execution environment: Host, Agent, Real
  2. Parsing of the source code
  3. Creation of meta-objects: Module Record / Script Record
  4. Program execution 4.1. Execution Preparation Phase 4.2. Instruction Execution Phase

Stage 1. Determination of the Execution Environment

Developer instructions (source text) cannot be executed in a vacuum. The specification defines three key layers of the execution environment:

  1. Host — the external program in which JavaScript code is executed: browsers, Node.js, Deno, etc.
  2. Agent — an isolated part of the execution environment (independent from other Agents) that has its own Execution Context Stack and Running Execution Context. Examples of agents include a browser tab, a Web Worker, or an iframe.
  3. Realm — a logical entity that defines the global object, global methods, and global variables, and is responsible for creating the Global Execution Context. In the V8 engine implementation, this corresponds to the v8::Context class (in C++).

Understanding the structure of the execution environment and its isolation model explains:

  • the absence of race conditions between tabs in the same browser;
  • why a Worker has no access to the global object and variables of the main application;
  • the isolation of overridden global JavaScript methods within a single Host.

Useful Links

Top comments (0)