Modules
Objectives
By the end of this lesson, you should be able to:
- Export values, functions, and a default export from a file
- Import them into another file, by name and by default
- Explain why splitting code across files matters as a project grows
💡 Why this matters: No real application lives in a single file. This lesson reviews the
import/exportsyntax itself, as a JavaScript language feature, the next module covers exactly how Node.js supports this alongside its older module system.
⚠️ A note on verification: every snippet and output in this lesson was actually run with Node.js.
Exporting
// mathUtils.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
export default function multiply(a, b) {
return a * b;
}
A file can have any number of named exports (add, PI here), plus at most one default export (multiply here). Named exports are for when a file provides several related things, a default export is for when a file’s main purpose is providing one specific thing.
Importing
// useMath.js
import multiply, { add, PI } from './mathUtils.js';
console.log(add(2, 3));
console.log(PI);
console.log(multiply(4, 5));
5
3.14159
20
Named exports are imported inside curly braces, matching the exported name exactly ({ add, PI }). A default export is imported without braces, and can be given any name on import, multiply here happens to match, but import doMultiply from './mathUtils.js' would work identically, since a default export has no fixed name to match against.
Why Split Code Across Files
A single file holding every function, class, and constant in an application quickly becomes impossible to navigate. Splitting code into modules, one file per logical piece, a set of utility functions, a class, a group of related constants, keeps each file focused and makes it obvious where to find (or add) something specific. This becomes essential once real project structure enters the picture, in Module 10.
Try It
- Create a file
stringUtils.jswith two named exports,capitalizeandreverse, each taking a string and returning a transformed version. - Create a second file that imports both functions and uses them on a sample string.
- Add a default export to
stringUtils.js, a function calledtruncate, and import it alongside the two named exports in the sameimportstatement. - Explain, in your own words, when you’d choose a default export over a named export for a given piece of code.
Recap
export(named) andexport default(at most one per file) make code in one file available to others.import { name } from './file.js'imports a named export,import anyName from './file.js'imports the default export.- Splitting code into focused modules keeps a growing project navigable, this becomes essential as an application scales.
Next lesson: working with objects and arrays, the methods used constantly in real code.