Engines, Node and the Browser

The first lesson said that the last section would explain how Node.js and the browser fit together. Here is that picture.

A program that runs JavaScript code is called a JavaScript engine. The engine you used in this course is V8. Google built it for the Chrome browser and made it open source. Node.js uses V8 too. Other browsers have their own engines: Firefox uses SpiderMonkey and Safari uses JavaScriptCore. They all run the same language.

An engine does not simply read your code line by line. It turns your code into machine code, the instructions the computer's processor runs. And it does this while the program runs. This is called just-in-time compilation. The engine also watches which functions run often and makes those faster. This is a big reason why JavaScript is fast enough for large apps in a browser tab.

Around the engine is a host, the program that the engine runs inside. The engine gives you the language itself: everything in this course, from arrays to closures to promises. The host adds extra tools on top:

  +---------------- your code ----------------+
  |  the language, run by the engine:         |
  |  objects, functions, classes, promises,   |
  |  JSON...                                  |
  +---------------------+---------------------+
  browser host          |  Node.js host
  document (the page),  |  require, files (fs),
  fetch, clicks,        |  servers, npm
  localStorage          |

You can see this in your own code. Node.js has require, which you used to read input. It has no document, because there is no web page:

console.log(typeof require);
console.log(typeof document);

Output:

function
undefined

In a browser it is the other way around. document is the web page, as objects that your code can read and change. It is called the DOM. For example, document.querySelector(".price").textContent = "9.99" finds an element on the page and changes the text that people see. The DOM is part of the browser, not part of the language. Node.js gives you other tools instead, like the fs module for files. This also explains the input line from your exercises. require("fs") loads the fs module from Node.js, and its readFileSync(0, "utf8") reads standard input.

One more layer completes the picture. The language itself is defined by a standard called ECMAScript. All engines follow it. A new version comes out every year. For example, toSorted from the Arrays section was added in ECMAScript 2023. To check which features work where, use the MDN Web Docs.

The exercise asks how the same JavaScript file runs in Chrome and in Node.js.