Node.js vs JS in the Browser

Most people transition from using JavaScript in the browser to Node.js. It's important to understand the differences between these two environments. It will help you create a clear mental model of what you can and can't do in Node.js compared to browser-based JavaScript.

Let's start by looking at some browser-specific JavaScript features:

Browser JavaScript

JavaScript's primary focus in the browser is manipulating the Document Object Model (DOM), handling user interactions, and facilitating communication with web servers.

Let's look at some of those key features that you won't find in Node.js:

DOM Manipulation

Its ability to interact with the DOM is at the heart of browser JavaScript. This allows developers to modify HTML elements, change styles dynamically, and respond to user actions. For example:

document.getElementById('myButton').addEventListener('click', function() {
  document.body.style.backgroundColor = 'blue';
});

When you take JavaScript out of the browser you'll no longer have the DOM to work with.

Web Platform APIs

Browsers provide a rich set of APIs that JavaScript can leverage. These include:

  • localStorage and sessionStorage for client-side data persistence
  • WebSocket for real-time communication
  • Geolocation for accessing user location data

Window Object

In browser JavaScript, window serves as the global object. It represents the browser window and provides access to browser-specific functions:

window.alert('Hello, world!');
let currentURL = window.location.href;

Security Sandbox

Browser JavaScript operates within a security sandbox, limiting its access to the user's system to prevent malicious actions. This limits the harm JavaScript can do to the system it runs on. Security can be a little easier to mess up once you take away this sandbox with Node.js.

Node.js

Since Node.js takes JavaScript beyond the browser it provides a runtime environment that allows JavaScript to interact with the operating system, file system, and network. Although you lose the goods the browser gives you, it opens up new possibilities.

Here are some of the key features you get from Node.js:

System-Level Operations

Node.js offers APIs for file system access, networking, and other low-level system operations. As an example, if you had a file on your system called example.txt you could read the data from it using the following:

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Process Information and Control

Node.js provides the process object, which allows you to interact with the current Node.js process. This includes access to environment variables, command-line arguments, and more.

Here's some code that will look alien compared to most browser JS code:

console.log(process.env.NODE_ENV); // Access environment variables
console.log(process.argv); // Access command-line arguments

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});

We will use the process object a little later to build our own interactive command line tool.

Global Object

In Node.js, the global object is aptly named global, is somewhat similar to the browser's window object. In the next section I'll compare and contrast.

Global Object: Window vs. Global

One of the key differences between browser JavaScript and Node.js is the global object they use.

In the Browser

In browser JavaScript, the global object is window. This object represents the browser window and provides access to browser-specific properties and methods.

console.log(window); // Outputs the window object
console.log(window.innerWidth); // Outputs the width of the browser window
window.alert("Hello!"); // Shows an alert dialog

In the browser, global variables and functions become properties of the window object:

let globalVar = "I'm global";
function globalFunction() {
    console.log("I'm also global");
}

console.log(window.globalVar); // Outputs: "I'm global"
window.globalFunction(); // Outputs: "I'm also global"

In Node.js

Node.js doesn't have a window object. Instead, it has a global object named global. However, the behavior is slightly different:

console.log(global); // Outputs the global object

// But variables are not automatically added to the global object
var globalVar = "I'm global";
console.log(global.globalVar); // Outputs: undefined

// Functions are also not automatically added to the global object
function globalFunction() {
    console.log("I'm global");
}
console.log(global.globalFunction); // Outputs: undefined

In Node.js, to make a variable or function global, you need to add it to the global object explicitly:

global.globalVar = "Now I'm truly global";
global.globalFunction = function() {
    console.log("Now I'm truly global");
};

console.log(global.globalVar); // Outputs: "Now I'm truly global"
global.globalFunction(); // Outputs: "Now I'm truly global"

It's important to note that in both environments, using global variables is generally discouraged as it can lead to naming conflicts and make code more challenging to maintain. But since it's syntax you might find in the wild I thought it's important to expose you to it.

Common Ground

Despite their differences, browser JavaScript and Node.js share a common foundation:

### Language Syntax

Both environments use the same JavaScript syntax, including variables, functions, and control structures.

ECMAScript Standards

They adhere to ECMAScript standards, supporting modern features like arrow functions, template literals, and destructuring.

npm Ecosystem

Many npm packages work in both environments, promoting code reuse and consistency.

Asynchronous Programming

Both support asynchronous operations using callbacks, Promises, and async/await syntax:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

So, as you can see, there are some core differences while working with each environment. We only covered some high-level differences, so you can have a mental model of some of the separations of running JS in the browser versus with Node.js. As you explore Node.js in more depth, you'll find more and more cool things you can achieve that wasn't possible in the browser.

BeginnerNodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.