1 · Get comfortable · 18 MIN
Understand imports and explicit exports
A module exposes only the values it deliberately exports.
An import declares where a dependency comes from. The node: prefix identifies a built-in Node module rather than an installed package. This example imports strict assertions to check a small function before printing its result. Exporting a function makes it available to other modules without adding it to a global object. You can later move total into a separate totals.mjs file and import it with a relative path including the extension. Modules help separate reusable calculation from terminal or HTTP concerns.
Read the built-in import before the function. Trace reduce with [2,3] starting from zero. Temporarily make the expected value wrong and read the assertion error. Restore the assertion before adding another test.
Before you start
Install Node.js 22.12+ (or a supported newer LTS). Create a folder named codingneed-node. Open a terminal in that folder. Save ONE lesson example as lesson.mjs and run node lesson.mjs. No npm dependencies are required. HTTP lessons keep running until you press Ctrl+C; stop the previous server before starting another.
File for this example: lesson.mjs
New words, explained
- module
- A file with its own scope and explicit imports and exports.
- export
- Make a binding available to another module.
- assertion
- A check that fails when an expected condition is false.
Follow the example step by step
- Read the built-in import before the function.
- Trace reduce with [2,3] starting from zero.
- Temporarily make the expected value wrong and read the assertion error.
- Restore the assertion before adding another test.
You are ready to move on when: The empty array returns zero. The negative-number assertion passes. Explain the difference between node: and a ./ relative import.
Read the example
import assert from 'node:assert/strict';
export function total(values) {
return values.reduce((sum, value) => sum + value, 0);
}
assert.equal(total([2, 3]), 5);
assert.equal(total([]), 0);
console.log('Total:', total([2, 3]));Check the expected output
Total: 5. If an assertion fails, Node reports the mismatch and exits with a failure.
Your challenge
Add a test for negative numbers. Optionally move the exported function into totals.mjs and import {total} from ./totals.mjs in lesson.mjs.
Solution cost: Discuss the operations in this small example; rendering and I/O costs depend on the host. time · Proportional to the example’s retained data. space
Common trap
Exporting a function does not call it. Importing a file can execute its top-level statements.
Study the project implementation
import assert from 'node:assert/strict';
export function total(values) {
return values.reduce((sum, value) => sum + value, 0);
}
assert.equal(total([2, 3]), 5);
assert.equal(total([]), 0);
console.log('Total:', total([2, 3]));Further reading: Official documentation
Next lesson: Wait for a promise without blocking JavaScript →