Skip to main content

Runtime

Engine and Runtime

JavaScript has two parts. One is the engine and the other is the runtime. The engine just parses, compiles, and runs the code. The runtime is the engine plus other libraries and parts, such as the event loop. Together they make JavaScript truly usable.

JavaScript Runtime

The web APIs here are the browser's APIs. They're registered into the global object of the engine.

DOM

The DOM object lives in the browser engine. It isn't part of JavaScript. JavaScript only has access to the browser's methods. Those methods then change the DOM object.

Embedded Library

Coming from a Java background, the JavaScript runtime is hard to grasp. The mental model doesn't fit what I have learned so far.

Keep one key point in mind. The JavaScript engine is added as a library in other apps. The host app that embeds the engine provides the runtime.

  1. Browser - JavaScript engine is added into browser's C++ application.
  2. NodeJS - JavaScript engine is compiled into NodeJS's C++ application.
Embedded Library

This is like maven libraries in Java. They're just added to the main app. The main app then hands requests to the engine.

It also provides the callback queue, the event loop, and other features. These form the runtime that schedules and runs code in the engine.

JavaScript in Java

To understand the embedding better, it helps to see how the JavaScript runtime works in Java.

With these libraries, Java adds Java-based functions to the JavaScript global object. They run when JavaScript calls the function.

Method Execution

The confusing part is this. The host app that embeds JavaScript backs the functions JavaScript calls. JavaScript just makes the calling code easy. But other languages do the real work.

In the browser, methods like setTimeout or fetch are written in C++. The C++ code runs them directly.

Callback Execution Flow

Callback Execution Flow

Native Methods

These are methods written in the language that embeds the engine. In Java, the SDK hides the low-level parts and gives us easy APIs.

For JavaScript, the idea is the same. The host language builds all the complex methods. We call them from the engine. This gives the illusion that the methods live in the JavaScript runtime.

Event Handlers

An HTML element is also a JavaScript object of type HTMLElement. When you add an event handler, it just adds a function property to that object with the given name.

When the handler fires, that object's function runs.