Sub topic 1
Engines, Runtimes, and Host Environments
Prerequisites
This chapter assumes you know basic JavaScript syntax (variables, functions, objects, arrays), have seen promises or callbacks, can read simple HTML, and can run commands in a terminal.
Engine Versus Runtime
A JavaScript engine is the program that parses and executes JavaScript. Examples are V8 in Chrome and Node.js, SpiderMonkey in Firefox, and JavaScriptCore in Safari. The engine implements only the language itself: syntax, objects, promises, and built-ins such as Array and JSON.
A runtime is an engine combined with host APIs, which are extra objects supplied by the environment around it. The browser adds document and navigator. Node.js adds process and modules such as fs. One common mistake is to treat setTimeout or console as part of the language. Both come from the host.
Running JavaScript in a Web Page
A classic <script> tag blocks HTML parsing while the script downloads and runs. defer runs the script after parsing finishes. async runs it as soon as it downloads, in no guaranteed order. A module script is deferred by default:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
<script type="module" src="main.js"></script>
</head>
<body>
<p id="out"></p>
</body>
</html>What the Browser Gives You: DOM and Web APIs
The DOM (Document Object Model) is the browser's object representation of the page. Web APIs such as fetch, localStorage, and navigator sit alongside it.
// main.js
const out = document.getElementById('out');
out.textContent = `Running in ${navigator.userAgent}`;Running JavaScript with Node.js
Node.js runs files from the terminal. Run node with no arguments to open the REPL, an interactive prompt that evaluates each line you type. process.argv holds the command-line arguments. Index 0 is the node executable, index 1 is the script path, and the user's arguments start at index 2.
// hello.js (run with: node hello.js Ada)
const name = process.argv[2] ?? 'world';
console.log(`Hello, ${name}!`);If you run main.js with Node.js, it throws ReferenceError: document is not defined, because Node.js does not provide the DOM.
Exercise
Moving a classic script tag from the end of the body into the head breaks document.getElementById('out'), which now returns null. Give two ways to fix it.
Show answer
Add defer to the tag, or change it to type="module". Both delay execution until the document has been parsed, so the element exists when the script runs.
Exercise
What does node hello.js print with no extra arguments, and why?
Show answer
It prints "Hello, world!". process.argv[2] is undefined, so the ?? operator falls back to 'world'.