liveBook · Manning

Live binding

As explained in Secrets of the JavaScript Ninja, Third Edition

A live binding is an imported reference to an exported variable whose current value reflects subsequent reassignment by the exporting module.

If a module exports a variable and later reassigns it, what does an importer see? In an ECMAScript Module (ESM), the import is a live binding: it reflects the exported variable’s current value. It is not a copied value or an ordinary variable the importer can reassign. section 13.1.1

Listing 13.7 Exporting a value that can be reassigned
const rollDice = () => {
  const roll1 = Math.ceil(Math.random() * 6);
  const roll2 = Math.ceil(Math.random() * 6);
  lastDiceRoll = roll1 + roll2;
  return lastDiceRoll;
};
let lastDiceRoll = -1;

export { rollDice, lastDiceRoll }; #A

The exporting module declares lastDiceRoll with let. Each call to rollDice assigns it a new result; an export list exposes both the function and variable. section 13.1.1

Listing 13.8 Importing a reassignable value
import {
  lastDiceRoll,
  rollDice,
} from "./7-random-export.ts";

for (let i = 0; i < 3; i++) {
  rollDice();
  console.log(lastDiceRoll);
}

The importing module calls rollDice three times and reads lastDiceRoll after each call. Each read sees the latest result. section 13.1.1

The distinction is who may assign. The exporting module can update its variable, but assigning to lastDiceRoll in the importing module raises a TypeError. Think of the import as a read-only proxy to the original variable—not as object destructuring, despite the similar-looking named-import syntax. section 13.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains the read-only proxy intuition through reassignment and a failed import assignment, without detailing module-loading internals.
Examples
Tracks three dice rolls through an imported variable and shows that assigning to the import raises a TypeError.
What it assumes
Assumes familiarity with let and import/export syntax while demonstrating export-list syntax before testing reassignment.
What you can do after
Diagnose/debug with it by distinguishing valid exporter reassignment from invalid importer assignment when an imported value changes.
How it connects
Connects live bindings to ESM named imports, export lists, let reassignment, and CommonJS module-object intuition.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.