Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Browser vs. Node.js: Understanding JavaScript Runtimes

This lesson is built with resources from youtube.com, freecodecamp.org and 1 more site.

Hello again! It's great to have you back for our third lesson.

In our previous session, we established what JavaScript is and its central role in making web pages interactive. We touched upon the idea that JavaScript can run in two different places: on the user's computer (the "client-side" browser) and on a remote computer (the "server-side").

Today, we're going to dive deep into that concept. This lesson focuses on the JavaScript runtime environmentโ€”the special "container" that your JavaScript code needs in order to be understood and executed by a computer. You'll learn to differentiate between the two most important runtimes: the Browser and Node.js.

Understanding this distinction is fundamental to your goal of learning Next.js, which cleverly uses both environments: Node.js for server-side operations and the browser for client-side interactivity.

What is a JavaScript Runtime Environment?

Before your JavaScript code can do anything, it needs an environment that provides all the necessary components to run it. Think of it like a fish tank: the fish (your code) needs the tank itself, water, an oxygen pump, and food to survive and function.

Similarly, a JavaScript runtime environment is the "tank" for your code. At its core, every JavaScript runtime includes a crucial component: the JavaScript Engine.

A JavaScript Engine is a program that reads your JavaScript code and translates it into instructions the computer's processor can execute. The most famous and widely used engine is Google's V8 engine, which powers both the Google Chrome browser and Node.js.

To get a quick visual overview of what a runtime is, let's watch a short segment from a video.

JavaScript Runtime Environment

This video, 'JavaScript Runtime Environment', introduces the concept of a runtime and lists its main components, providing a great starting point for our discussion.

Watch from 00:27 to 01:13. Focus on how the video defines a runtime environment and notes that the environments for the browser and Node.js are slightly different, even if their basic structure is the same.

Now that we have a basic definition, let's break down the two main environments, starting with JavaScript's original home.


1. The Browser Runtime Environment

When you visit a website, your browser (like Chrome, Firefox, or Safari) acts as a JavaScript runtime. It's designed to execute code that interacts with the web page you are seeing.

The browser runtime consists of a few key parts, which work together:

  1. The JS Engine (e.g., V8): The heart of the runtime, responsible for executing your code.
  2. Web APIs (Application Programming Interfaces): These are extra functionalities provided by the browser that are not part of the core JavaScript language. They act as a bridge, allowing your code to interact with the browser and the user's computer. Common Web APIs include:
    • The DOM (Document Object Model) API: Allows you to manipulate the HTML and CSS of the pageโ€”change text, add elements, modify styles, etc.
    • Timers (setTimeout, setInterval): Allow you to execute code after a delay or at regular intervals.
    • Fetch API: Allows you to make network requests to servers to send or receive data.
    • The window object: A global object that represents the browser window and provides access to all Web APIs. For example, console.log() is actually part of the window object (window.console.log()).
  3. The Callback Queue & Event Loop: These components handle asynchronous tasks. When you click a button or a timer finishes, the code that should run is placed in the Callback Queue. The Event Loop's job is to check if the JS Engine is idle and, if so, move tasks from the queue to be executed.

Because you appreciate visual explanations, here is a diagram that shows how all these pieces fit together inside the browser.

JavaScript Runtime Environment Diagram
This diagram shows the main components of the browser runtime. The **JS Engine** (containing the Call Stack and Heap for code execution and memory) works alongside **Web APIs** (like DOM and Timers). The **Event Loop** orchestrates the process by moving completed asynchronous tasks from the **Callback Queue** to the Call Stack.

To solidify your understanding of these browser runtime components, please read the following article from freeCodeCamp.

JavaScript Engine and Runtime Explained

The article 'JavaScript Engine and Runtime Explained' provides clear, illustrated explanations of the browser runtime's components. It's perfect for understanding how the engine and Web APIs interact.

Please read the sections 'What is a JavaScript Runtime?' and 'What is a JavaScript Runtime? - Continued' (this is a quirk in the article's formatting, but it's the section that details Web APIs, the callback queue, and the event loop). Focus on the diagrams and the explanation of how things like DOM events are handled.


2. The Node.js Runtime Environment

For many years, JavaScript could only run in browsers. This changed in 2009 with the creation of Node.js, a runtime environment that allows you to run JavaScript on a server. This was a revolutionary idea that enabled developers to use the same language for both the frontend (browser) and the backend (server).

The core philosophy of Node.js is non-blocking, event-driven I/O (Input/Output). In simple terms, this means Node.js is extremely efficient at handling tasks that involve waiting, like reading a file from a disk, querying a database, or fetching data from another service. Instead of freezing and waiting for a task to finish, it starts the task, moves on to other work, and gets notified when the original task is complete.

The Node.js runtime has a different architecture:

  1. The JS Engine (V8): The same high-performance engine found in Chrome. This is the key shared component.
  2. Node.js APIs & C++ Bindings: Since there is no browser, Node.js doesn't have Web APIs like the DOM or the window object. Instead, it provides its own set of powerful, built-in modules for server-side operations, such as:
    • fs (File System): For reading from and writing to files.
    • http: For creating web servers.
    • path: For working with file and directory paths.
  3. libuv: A C++ library that is the "secret sauce" of Node.js. It provides the event loop and handles asynchronous I/O operations in a non-blocking way, making Node.js fast and efficient for server applications.

Here is a simplified diagram of the Node.js architecture:

Node.js Runtime Architecture
This visual highlights the two main pillars of the Node.js runtime: the **V8 Engine** for executing JavaScript and **libuv** for managing asynchronous I/O and the event loop.

To explore the "why" behind Node.js and its architecture, the following resource provides a fantastic deep dive.

What Node.js Actually Is - NodeBook

The article 'What Node.js Actually Is' does an excellent job of explaining the history and core components of the Node.js runtime. It's perfect for understanding why Node.js was created and how it works under the hood.

First, read the 'TL;DR' section for a concise summary. Then, read the section titled 'The Core Components - V8, libuv, and the Glue'. This will give you a detailed breakdown of how V8, libuv, and the C++ bindings work together to create the Node.js runtime.

Test your understanding!

For each of the following tasks, decide whether it would be performed in a Browser runtime or a Node.js runtime.

  1. Making a button change color from blue to green when a user hovers their mouse over it.
  2. Saving a new user's account information to a central database.
  3. Resizing the browser window and having the layout of the page adjust automatically.
  4. Reading a configuration file from the server's hard drive when an application starts.
Show answer
  1. Browser: This is a classic user interface interaction. It involves listening for a hover event and manipulating CSS, which are tasks handled by the browser's Web APIs (specifically the DOM API).
  2. Node.js: Direct database access is a server-side responsibility. The Node.js application running on the server would receive a request from the browser and then use a database driver to save the information.
  3. Browser: This involves interacting with the browser window itself (window object) and manipulating the page's layout (DOM), which are exclusively browser capabilities.
  4. Node.js: Accessing the server's file system is a core feature of Node.js, handled by its fs (File System) module. A browser cannot arbitrarily access files on a server's hard drive for security reasons.

Key Differences Summarized

Feature Browser Runtime Node.js Runtime
Primary Purpose Client-side scripting, UI interactivity Server-side logic, APIs, file system access
Environment Runs inside a user's web browser Runs on a server or a developer's machine
Global Object window global
Key APIs DOM, Fetch, Timers, localStorage fs, http, path, process
Example Task Animate an element when a user scrolls Create a REST API to serve data to an app

Conclusion

You've now explored the two primary worlds where JavaScript lives. This understanding is critical as you move forward.

Key Takeaways:

  • A JavaScript runtime is an environment that provides a JS Engine and other tools to execute code.
  • The Browser runtime is specialized for client-side interaction, offering Web APIs like the DOM to manipulate web pages.
  • The Node.js runtime is specialized for server-side tasks, providing Node.js APIs like fs (File System) and http to build backends.
  • Both environments share the powerful V8 JavaScript Engine but are built for different purposes.

Now that you know where JavaScript code runs, the next logical step is to set up your own machine to start writing and executing it.

In our next lesson, we'll get practical by setting up your local development environment. We will install VS Code, the most popular code editor, and learn how to use the browser's consoleโ€”your very first playground for running JavaScript code.