Sub topic 8
Imports Are Live Bindings, Not Copies
This chapter assumes you know how to write named exports and imports, and how to run ES modules in Node.js or the browser. You should also know the difference between let and const.
The working model
An import does not copy a value. It creates a binding, which is a read-only reference to the variable that the exporting module declared. Whenever you read an imported name, you get the exporter's variable as it is at that moment. If the exporting module changes the variable later, every importer sees the new value.
Seeing it happen
// counter.js
export let count = 0;
export function increment() {
count += 1;
}// main.js
import { count, increment } from './counter.js';
console.log(count); // 0
increment();
console.log(count); // 1main.js never assigns to count, but the value it reads changes anyway. That is because count in main.js is the same variable as count in counter.js. A namespace import behaves the same way: after import * as counter from './counter.js', reading counter.count also gives the current value.
Bindings are read-only for importers
Only the module that declares a variable can reassign it. The following line throws a TypeError in main.js, even though counter.js declared count with let:
count = 5; // TypeError: Assignment to constant variable.If importers need to change state, export a function that does the change, as increment does above. That keeps all writes in the module that owns the state.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Copying the value into a local: `const snapshot = count;` | `snapshot` stops updating; it holds the value from when you copied it | Read the imported name directly whenever you need the current value |
| Destructuring a namespace: `const { count } = counter;` | Same as above: you get a copy | Use `counter.count` |
| Assigning to an import | `TypeError` | Export a setter function |
| Expecting CommonJS behavior | `const { count } = require(...)` copies; ESM does not | Do not port CommonJS code on the assumption that the two behave the same |
The difference from CommonJS is the main reason to know this. Code that depended on a value being copied at require time can behave differently after you convert it to ES modules.
Exercise
counter.js exports let count = 0 and increment(). main.js runs import * as c from './counter.js'; const { count } = c; c.increment(); console.log(count, c.count); What does it print, and why?
Show answer
It prints 0 1. Destructuring copies the value of c.count into a new local constant, count, at that moment. c.count reads the live binding, so it shows the updated value after increment() runs.
Exercise
Why does count = 5 in main.js throw, even though counter.js declared count with let?
Show answer
An imported binding is always read-only in the importing module. Only the module that declared the variable can reassign it, so main.js has to call an exported function such as increment() to change it.