Modules
A module is a single file with its own scope that explicitly declares what it exposes with export and what it needs with import. Nothing is shared unless it is exported.
Detailed Explanation
Before modules, every <script> tag in a page shared one global scope. Two files declaring const config collided. Load order was a manual dependency graph maintained by hand in HTML. Developers worked around this with the IIFE module pattern, wrapping each file in an immediately invoked function so its variables stayed private and attaching one object to window. ES2015 made modules part of the language.
Every module has its own scope. A top-level const in a module is local to that file, not global. To share something you export it; to use it you import it.
There are two export styles. Named exports — export function parse() {} or export { parse, format } — can be many per file and are imported by exact name inside braces. A default export — export default function () {} — is one per file and is imported without braces under any name you choose. Named exports are usually better: the name is fixed, so renames and typos are caught, and bundlers can eliminate unused code more reliably.
Four properties of ES modules matter more than the syntax.
Static structure. import and export must appear at the top level. They cannot be inside an if, a function, or a try. This is a deliberate restriction: it lets tools determine the entire dependency graph without running the code, which is what makes tree-shaking and static type checking possible. When you genuinely need a conditional or lazy load, use dynamic import(), which is a function-like form returning a promise and is allowed anywhere.
Hoisted imports. All imports are resolved and their modules evaluated before any statement in the importing file runs. Placing an import at the bottom of the file changes nothing.
Live bindings. An import is not a copy of the value. It is a read-only view onto the exporting module's variable. If the exporter later reassigns it, importers see the new value immediately. You cannot assign to an imported binding; that is a TypeError.
Single evaluation. A module is fetched, parsed, and executed once per specifier for the lifetime of the program, no matter how many files import it. The resulting namespace is cached. This is why a module's top-level code is a natural place for a singleton, and also why top-level side effects are hard to reason about.
Two more behaviours. ES modules are always in strict mode; you never write "use strict" in one, and this at the top level is undefined rather than the global object. And modules support top-level await, so a module can await a value before its exports become available — at the price of delaying every module that imports it.
Circular imports are legal and do not crash, but a module that reads an imported binding during its own initialisation may find it uninitialised and hit a temporal dead zone error. Function declarations survive cycles because they hoist; const values often do not.
Code Examples
currency.js — named exports, and a binding that changes after export.
// currency.js — named exports, and a binding that changes after export.
export const SUPPORTED = ["GBP", "USD"];
export let rate = 1.0; // exported binding, not a snapshot
export function setRate(next) {
rate = next; // importers observe this immediately
}
export function format(amount, code = "GBP") {
return `${code} ${amount.toFixed(2)}`;
}
// A default export: one per file, imported under any name.
export default function convert(amount, r = rate) {
return amount * r;
}app.js — imports are hoisted and evaluated before this line runs.
// app.js — imports are hoisted and evaluated before this line runs.
import convert, { rate, setRate, format } from "./currency.js";
// ^default ^named exports must match the exported names
console.log(format(12.5)); // => GBP 12.50
console.log(rate); // => 1
setRate(0.79);
console.log(rate); // => 0.79 live binding, not a copy
// rate = 2; // TypeError: Assignment to constant variable
// Dynamic import for conditional or lazy loading. Returns a promise.
if (process.argv.includes("--charts")) {
const { renderChart } = await import("./charts.js"); // top-level await
renderChart();
}Common Gotchas
Imported bindings are read-only
assigning to an imported name throws a `TypeError`. Export a setter function instead.
Imports are hoisted and static
you cannot put `import` inside an `if` or a function, and moving it lower in the file does not delay it. Use `import()` for conditional loading.
Circular imports can yield uninitialised values
a `const` read during a cycle's initialisation throws a temporal dead zone error. Hoisted function declarations are safe.
Modules are always strict
`this` is `undefined` at the top level and sloppy-mode behaviour is unavailable. In a browser you must load them with `<script type="module">`.