Browser vs Node.js
Introduction
The same language runs in two very different homes. In the browser, JavaScript manipulates web pages and talks to the user. In Node.js, it runs on a server with access to the filesystem, network sockets, and the operating system.
Both embed a JS engine (usually V8) but surround it with different host APIs.
Why This Matters
Confusing browser and Node APIs is a classic bug source: window and document don't exist in Node; require/fs/process don't exist in the browser. Interviewers use this to check whether you understand that the engine is not the environment.
Theory
What they share
- The ECMAScript language itself (syntax, types,
Promise,Array,JSON). - A JS engine (V8 in Chrome and Node).
- The event loop model (though the implementations differ — libuv in Node).
What differs
| Concern | Browser | Node.js |
|---|---|---|
| Global object | window / self | global / globalThis |
| DOM | document, window | none |
| Timers | setTimeout, setInterval | same names, libuv-backed |
| Networking | fetch, XMLHttpRequest | http, fetch (v18+), sockets |
| Filesystem | none (sandboxed) | fs |
| Modules | ES Modules (import) | CommonJS (require) and ESM |
| Process info | none | process, process.env |
| Event loop impl | browser-provided | libuv |
globalThis
Because the global object has different names, ES2020 added globalThis — a single, portable reference that works in both environments.
Code Examples
Write environment-agnostic code
Use globalThis and feature detection so a module works in both the browser and Node:
Interview Questions
1What is the difference between JavaScript in the browser and in Node.js?
Both run the same ECMAScript language on a JS engine (V8), but provide different host APIs. The browser exposes the DOM, window, fetch, and localStorage, and sandboxes the filesystem. Node exposes fs, http, process, and require, and uses libuv for its event loop. Code that assumes window/document breaks in Node, and code that assumes fs/require breaks in the browser. globalThis gives a portable global reference.
2Does Node.js use the same event loop as the browser?
The concept is the same (a loop that processes queued callbacks), but the implementation differs. Node's event loop is provided by libuv and has distinct phases (timers, poll, check, close) plus process.nextTick and microtask handling. The browser's event loop is defined by the HTML spec and integrates rendering.
Quiz
1. Which of these exists in the browser but NOT in Node.js?
Summary
- Browser and Node run the same language but expose different host APIs.
- Browser: DOM, window, fetch, localStorage. Node: fs, http, process, require.
- Node's event loop is implemented by libuv; the browser's by the HTML spec.
- Use globalThis and feature detection for portable code.