Modules
Split code across files with import and export.
- Export values from a file and import them elsewhere
- Distinguish named exports from default exports
- Explain why modules keep code organised
As a program grows past one file, ES modules keep it organised: each file owns a
focused job (cohesion) and exposes a small set of names for others to use (its
interface). JavaScript's module system is import / export.
Named exports
Mark anything you want to share with export, and import it by name:
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// app.js
import { add, PI } from "./math.js";
add(2, 3); // 5The names in the { } must match the exported names. You can rename on import
with as: import { add as sum } from "./math.js".
Default exports
A module can have one default export — useful when a file is "about" one main thing:
// logger.js
export default function log(msg) {
console.log("[app]", msg);
}
// app.js
import log from "./logger.js"; // no braces; you choose the nameUse named exports for a module that provides several things; a default export for a module whose whole purpose is one value (a component, a class, a main function).
Why modules matter
Modules are how the abstraction and architecture lessons play out in real code: each file hides its internals and offers a clear surface, so you can change one without breaking the others, and a reader can understand a file from its exports alone.
This is also the foundation of the whole npm ecosystem: third-party packages are
just modules you import. import { useState } from "react" is the same
mechanism, pointing at an installed package instead of a local file.
Where to go next
Last in Language basics: TypeScript basics — adding a type layer that catches mistakes before you run.