Browser vs Node.js

JavaScript runs in two main environments: Browser and Node.js. Understanding their differences helps you write code suitable for each platform.

Core Differences
AspectBrowserNode.js
EnvironmentClient-side (web browsers)Server-side (runtime on machines)
APIsDOM, BOM, Fetch, WindowFile system, Network, Process, OS
Global Objectwindowglobal
Module SystemES Modules, script tagsCommonJS (require), ES Modules
Use CasesInteractive web pages, UIBackend servers, scripts, tools
SecuritySandboxed, restricted accessFull system access

While the core JavaScript language remains the same, the available APIs and context differ significantly.

Illustration of Browser vs Node.js
Illustration of Browser vs Node.js

💡 Global Object Differences

In browsers, the global object is window, which includes DOM and Web APIs. In Node.js, it's global, providing access to system-level modules.

Browser JavaScript can manipulate HTML elements and respond to user events, but cannot access the file system or run background processes. Node.js is designed for server-side tasks like reading files, creating servers, and handling databases.

📌 Deep Dive: Accessing Global Object

JAVASCRIPT
console.log(window); // Browser global object
console.log(global); // Node.js global object
Output
Browser: Window object with DOM APIs
Node.js: Global object with system APIs

⚠️ API Availability

Don't assume browser APIs like document or fetch are available in Node.js, or Node.js APIs like fs are available in browsers.

To summarize:

  • Browser JavaScript is optimized for UI interactions.
  • Node.js is built for backend and scripting tasks.
  • They share the same JavaScript language but differ in environment and APIs.