Intermediate 8 min

JavaScript modules and imports

Modules let you expose selected values to other files and keep the rest local.

How it works

Export only the parts of a module that another file needs. A small math module can keep a helper private while exporting add. The importing file asks for the exported name explicitly, which makes the dependency easier to see.

Walk through an example

Write export function add(a, b) in math.js. Another module imports it with import { add } from './math.js'. Browser scripts can opt into modules with type="module".

What to watch for

A named import must match the exported name unless you rename it with as. Paths are resolved relative to the importing module for relative imports.

Check your understanding

How do you write the import?

See the example and explanation
Worked example
Given math.js exports add; another file needs it under the name sum.
Answer import { add as sum } from './math.js';

The real export is named add. The as clause gives it a different name in the importing file.

Open practice problem
Next lessonFetch, HTTP errors, and cancellation