Summary - Modules
- JavaScript course
- Intermediate
- Lesson 129/134
- 5 min
Build a simple two-file calculator module using named and default export/import.
Summary - Calculator module
In this summary you will build a two-file calculator module: calc.js exports the operations, main.js imports and uses them.
Inside calc.js the functions add and subtract are named exports and calculate is the default export. main.js pulls them in one import line and shows the result with console.log.
This mirrors how real projects wire files together.
Practice Write the calc.js module
Write a calc.js module: export add and subtract as named exports, and calculate as the default export. calculate takes an op and two numbers.
Starter code
// calc.js — calculator moduleSample solution
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export default function calculate(op, a, b) {
if (op === "+") return add(a, b);
if (op === "-") return subtract(a, b);
return 0;
}main.js imports
The main.js file imports values from calc.js. You can combine named and default imports in one line.
import calculate, { add, subtract } from './calc.js';Then you call calculate and log the result:
console.log(calculate("+", 5, 3));This shows how modules find and use each other.
Practice Write the main.js import
In main.js, import add and subtract as named and calculate as default from ./calc.js. Then log the result of calculate("+", 5, 3) with console.log.
Starter code
// main.js — import from calc.jsSample solution
import calculate, { add, subtract } from './calc.js';
console.log(calculate("+", 5, 3));Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can a module have both named and default exports?
- No, only one type
- Yes, both together Correct answer
- Only named
- Only default
Explanation: A module can have both named and default exports.
2 Match the export/import types
| Term | Meaning |
|---|---|
named export |
by name |
default export |
one per module |
named import |
with { } |
default import |
no name needed |