Sub topic 8
Imports Are Live Bindings, Not Copies
This chapter assumes you know the import and export forms from the earlier chapters. You should also know how let and const differ and how to run an ES module in Node.js or the browser. To run the examples in Node.js, put them in a folder whose package.json contains "type": "module", or rename the files to .mjs and update the import paths.
Most JavaScript developers already know that assigning a primitive copies it. Writing let b = a and then changing a does not change b. Imports work differently. An imported name is a binding: a reference to a variable that lives inside the exporting module. The importer has no copy of its own. It looks into the exporter's variable each time the name is read. This explains several behaviors that look odd at first.
The working model
Each module has its own module environment, which is the scope that holds its top-level variables. When main.js imports count from counter.js, the engine does not create a new variable in main.js. It links the name count in main.js to the count slot in counter.js's environment.
Two rules follow from this model:
- Live: when the exporter changes the variable, every importer sees the new value on its next read.
- Read-only: only the exporting module can assign to the variable. An importer that tries gets a
TypeError.
Seeing liveness in action
// 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); // 1
increment();
console.log(count); // 2main.js never assigns to count, yet its value changes. increment updates the variable in counter.js, and main.js reads that same variable.
Read-only means the binding, not the value
Uncomment an assignment and the module fails:
// main.js
import { count } from './counter.js';
try {
count = 5;
} catch (error) {
console.log(error instanceof TypeError); // true
}An import behaves like a const binding that only the exporter can write to. This rule protects the binding and nothing else. If the exported value is an object, any importer can change its properties:
// settings.js
export const settings = { theme: 'light' };// main.js
import { settings } from './settings.js';
import './other.js';
settings.theme = 'dark'; // allowed: this mutates the shared object
console.log(settings.theme); // 'dark'
// settings = {}; // TypeError: cannot reassign the bindingA module is evaluated once per program, so every importer of settings.js shares that one object. A mutation in one file is visible in all the others. This is useful for deliberate shared state. It is a hard bug to find when it happens by accident. If importers should not change an exported object, freeze it with Object.freeze or export a function that returns a fresh copy.
Namespace imports are live too
A namespace import (import * as ns) gives you a module namespace object. Its properties are getters over the same bindings, so they stay live. The object itself is sealed: you cannot add, delete, or assign properties. Module code always runs in strict mode, so assigning a property throws.
// main.js
import * as counter from './counter.js';
counter.increment();
console.log(counter.count); // 1
try {
counter.count = 10;
} catch (error) {
console.log(error instanceof TypeError); // true
}Where liveness is lost
Liveness belongs to the import binding. Once you copy the value into an ordinary variable, you have a plain snapshot again. These are the common ways that happens.
Destructuring or assigning the value
// main.js
import * as counter from './counter.js';
const { count } = counter; // copies the current value, 0
let saved = counter.count; // also a copy
counter.increment();
console.log(count, saved, counter.count); // 0 0 1`export default` with an expression
export default <expression> evaluates the expression once and stores the result in a hidden binding. If you later reassign the original variable, the default export does not change. Exporting the variable under the name default keeps it live.
// value.js
export let value = 1;
export default value; // snapshot: the default is 1 from now on
export { value as current }; // live alias of value
export function bump() {
value += 1;
}// main.js
import snapshot, { value, current, bump } from './value.js';
bump();
console.log(snapshot, value, current); // 1 2 2export { value as default } would make the default export live as well. export default function name() {} and export default class Name {} are declarations. They export the binding itself, so reassigning name inside the module would show up in importers.
Comparison with CommonJS
CommonJS require returns whatever module.exports holds. A primitive placed on that object is copied at the moment of assignment:
// counter.cjs
let count = 0;
function increment() {
count += 1;
}
module.exports = { count, increment };// main.cjs
const counter = require('./counter.cjs');
counter.increment();
console.log(counter.count); // 0: the object holds a copy made at export timeTo get similar behavior in CommonJS, you would expose a getter or a function such as getCount(). This difference matters when you migrate code between the two systems. A CommonJS pattern that relied on a snapshot can start behaving differently after conversion, and the reverse is also true.
Summary of behaviors
| Situation | Live? | Can the importer reassign it? |
|---|---|---|
| `import { x }` | Yes | No (`TypeError`) |
| `import * as ns` then `ns.x` | Yes | No (`TypeError`) |
| `const { x } = ns` | No, snapshot | Yes, it is a local variable |
| `export default x` (expression) | No, snapshot at evaluation time | No |
| `export { x as default }` | Yes | No |
| Mutating properties of an imported object | Shared by all importers | Properties yes, binding no |
| CommonJS `module.exports = { x }` | No, copy | Yes |
Why the language works this way
Live bindings are the reason linking can happen before evaluation. The engine connects every import to its export slot first, then runs the module code. Because importers hold references and not values, those references can exist before the exporter has run. This is also why a circular dependency can reach a const that has not been initialized yet and throw a temporal dead zone error. The later chapters on the module lifecycle and circular dependencies cover that in detail.
Exercise
Given // state.js containing export let n = 1; export default n; export function set(v) { n = v; }, what does import d, * as s from './state.js'; const { n } = s; s.set(7); console.log(d, n, s.n); print?
Show answer
It prints 1 1 7. The default export took a snapshot of n when export default n ran. The destructured n copied the value 1 before set was called. s.n reads the live binding, which is now 7.
Exercise
A teammate writes import { cache } from './cache.js'; cache = new Map(); to reset a shared cache, and it throws. Explain why, and give two ways to reset the cache that work.
Show answer
Imported bindings are read-only, so reassigning cache in the importer throws a TypeError. One fix is to mutate the shared object with cache.clear(), which every importer will see. The other is to have cache.js export a function such as export function resetCache() { cache = new Map(); } (with cache declared using let). Because the binding is live, every importer will then see the new Map.
Exercise
Why does a CommonJS module that runs module.exports = { count } and later increments count not show the new value to require callers, while the same pattern written with export let count does?
Show answer
CommonJS copies the current value of count into a property of the exports object, and callers read that property. An ES module import is linked to the exporter's variable itself, so every read returns its current value.