Sub topic 1
Engines, Runtimes, and Host Environments
When people say "JavaScript runs in the browser" or "JavaScript runs in Node.js", they are describing two separate layers as if they were one. The first layer is the engine, which understands the JavaScript language. The second is the host environment, which gives the language a way to touch the outside world. Together they form a runtime. This chapter separates those layers so the rest of the tutorial has a clear model to build on.
Prerequisites
This chapter assumes you can already:
- Read and write basic JavaScript: variables, functions, objects, and arrays.
- Recognize promises or callbacks, even if you are not fully comfortable with them yet.
- Read a simple HTML document.
- Open a terminal and run a command such as
node --version.
You need Node.js 18 or later installed to run the examples, plus any modern browser.
What an Engine Does
A JavaScript engine is a program that takes JavaScript source text and executes it. Its responsibilities are defined by the ECMAScript specification (ECMA-262), the standard that describes the language itself. An engine:
- Parses source text into an internal representation, usually an abstract syntax tree.
- Compiles and executes that representation. Modern engines start with an interpreter that produces bytecode, then use one or more just-in-time (JIT) compilers to turn frequently run code into optimized machine code.
- Manages memory with a garbage collector, which frees objects that no code can reach any more.
- Provides the built-in objects the specification requires:
Object,Array,String,Map,Set,Promise,JSON,Math,Date,RegExp,Proxy, and others.
An engine does not do some things. It has no concept of files, network sockets, screens, keyboards, or clocks that fire callbacks. The ECMAScript specification contains no function for printing text, reading a file, or waiting 100 milliseconds. A bare engine can compute [3, 1, 2].sort(), but it has no way to show you the result.
The major engines
| Engine | Maintained by | Used in |
|---|---|---|
| V8 | Chrome, Edge, Opera, Node.js, Deno | |
| SpiderMonkey | Mozilla | Firefox |
| JavaScriptCore | Apple | Safari, Bun |
The same engine can sit inside very different products. Chrome and Node.js both use V8, so they agree on language behaviour such as how Array.prototype.sort orders elements or which syntax is supported in a given version. They disagree on almost everything to do with the outside world.
Engines are shipped as libraries. A host program links the library, creates an engine instance, and calls into it to run code. Inside V8 an instance is called an isolate, and each isolate has its own heap and garbage collector. A browser tab, a Web Worker, and a Node.js worker thread each run on a separate engine instance. This is why their variables are not shared.
What a Host Environment Adds
The host environment is the program that embeds the engine. It adds three things the language lacks.
- Host APIs. These are extra objects and functions placed on the global object or made available as modules. The browser adds
document,window,fetch,localStorage, andsetTimeout. Node.js addsprocess,Buffer,setTimeout, and modules such asnode:fsandnode:http. - An event loop. ECMAScript defines jobs, such as the callbacks a promise schedules when it settles, but it leaves the host to decide when those jobs run and how they fit with timers, network events, and user input. Each host implements its own loop. Chapter 7 covers this in detail.
- A way to load code. The engine can compile a string of source text. Where that text comes from is the host's job: a
<script>tag, a file path passed tonode, or animportstatement that the host resolves to a URL or file.
So the working model is:
runtime = engine + host APIs + event loop + module loader
Shared names, separate implementations
Some host APIs have the same name in both environments. setTimeout, console.log, fetch, URL, TextEncoder, and structuredClone exist in modern browsers and in Node.js. They are still host APIs, not language features. Each host implements them separately, often following a web standard (WHATWG or W3C) and not ECMAScript. The details can differ. In a browser, setTimeout returns a number. In Node.js it returns a Timeout object with methods such as unref().
Seeing the Layers for Yourself
The script below sorts globals into those the language guarantees and those a host might provide, then reports which ones the current runtime actually has. Save it as probe.js.
// probe.js
const language = ['Object', 'Array', 'Promise', 'Map', 'JSON', 'Math', 'Proxy'];
const host = [
'console', 'setTimeout', 'fetch', 'URL', 'structuredClone',
'document', 'window', 'localStorage',
'process', 'Buffer',
];
function report(label, names) {
console.log(`\n${label}`);
for (const name of names) {
const kind = typeof globalThis[name];
console.log(` ${name.padEnd(16)} ${kind}`);
}
}
report('Defined by ECMAScript (every engine):', language);
report('Provided by the host (varies):', host);Run it with Node.js:
node probe.jsThen paste the same code into the Console tab of your browser's DevTools. The first group reports function or object in both places. In the second group, document, window, and localStorage are undefined in Node.js, and process and Buffer are undefined in the browser. fetch, URL, and structuredClone appear in both, because both hosts chose to implement those web standards.
You can also ask Node.js which engine version it embeds:
node -p "process.versions"The output lists node, v8, uv (libuv, the library behind the Node.js event loop and file system access), and other components. In the browser, the engine version follows the browser version. Chrome 120 ships V8 12.0, for example.
Common Errors and What They Mean
Most beginner confusion between environments comes from calling a host API in a host that doesn't provide it. The engine reports that as an ordinary missing variable.
| Error message | Where you see it | Actual cause |
|---|---|---|
| `ReferenceError: document is not defined` | Node.js | DOM APIs come from the browser host. Node.js has no page. |
| `ReferenceError: window is not defined` | Node.js | `window` is the browser's global object. Use `globalThis` for portable code. |
| `ReferenceError: process is not defined` | Browser | `process` is a Node.js host object. Bundlers sometimes fake it, but browsers don't provide it. |
| `ReferenceError: require is not defined` | Browser, or a Node.js ES module | `require` is supplied by the CommonJS module wrapper in Node.js. It is not a global (see Chapter 6). |
| `SyntaxError: Unexpected token` on new syntax | Older runtime | The *engine* version is too old for that syntax. This is an engine issue, not a host issue. |
The last row matters for diagnosis. A SyntaxError on valid modern code points to the engine version. A ReferenceError on a well-known name usually means the code is running in the wrong host.
Edge Cases Worth Knowing
Same engine, different behaviour
Chrome and Node.js both run V8, but they can ship different V8 versions. Node.js 18 shipped V8 10.2, while Chrome had already moved far past that. A language feature can work in your browser and fail in an older Node.js, or the reverse. Check process.versions.v8 or the Node.js release notes before relying on new syntax.
Engine flags versus host features
Some behaviour can be changed with engine flags. For example, node --stack-trace-limit=50 app.js passes an option straight to V8. Other options, such as node --watch, belong to the Node.js host. Both kinds of option sit on the same command line, so this is easy to miss.
Other runtimes
Deno (V8) and Bun (JavaScriptCore) are further runtimes. They follow the same model with different host APIs. Deno exposes a Deno global, and Bun exposes a Bun global. Both also implement many web standards such as fetch. Cloudflare Workers and similar edge platforms run V8 isolates with a small, mostly web-standard host API. The engine-versus-host model applies to all of them, which is why learning it pays off beyond this tutorial.
Strictly language-level code is portable
Code that uses only ECMAScript built-ins, such as a function that sorts, filters, or formats data, runs unchanged in every runtime. Portability problems begin when code reaches for a host API. Chapter 10 builds on this to write modules that run everywhere.
Summary of the Model
- The engine implements ECMAScript: syntax, execution, garbage collection, and built-in objects.
- The host embeds the engine and adds I/O APIs, an event loop, and a way to load code.
- A runtime is the combination, and "browser" and "Node.js" are two different runtimes that often share an engine.
- When something is missing, decide which layer it belongs to before you look for a fix.
Exercise
Classify each of these as provided by the engine (ECMAScript) or by the host: Array.prototype.map, setTimeout, JSON.parse, fetch, Promise, process.argv, document.querySelector.
Show answer
Engine: Array.prototype.map, JSON.parse, Promise. Host: setTimeout, fetch, process.argv (Node.js only), document.querySelector (browser only). setTimeout and fetch exist in both browsers and Node.js, but each host implements them separately and ECMAScript does not define them.
Exercise
A teammate runs a script in Node.js and gets ReferenceError: localStorage is not defined. They suggest upgrading Node.js to a newer V8 version. Is that the right fix? Explain.
Show answer
Probably not. localStorage is a browser host API, not a language feature, so the V8 version is irrelevant. The fix is to use a Node.js mechanism for storage, such as writing a file with node:fs, or to move the code to the browser. A newer engine helps with SyntaxErrors on modern syntax, not with missing host APIs.
Exercise
Chrome and Node.js both use V8. Give two reasons the same piece of code might behave differently in them.
Show answer
First, they may ship different V8 versions, so newer syntax or built-ins may exist in one and not the other. Second, they have different hosts: the available globals (document versus process), the event loop implementation, the module loading rules, and the details of shared APIs (for example, setTimeout returning a number versus a Timeout object) all differ.