Summary - Modules
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.
Exercise 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.
Show example solution
Write two named export functions and one default export function. calculate takes an op and two numbers.
Example 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.
Exercise 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.
Show example solution
Separate the default name and the named list in braces with a comma. Then call calculate.
Example solution:
import calculate, { add, subtract } from './calc.js';
console.log(calculate("+", 5, 3));
Test yourself
-
Can a module have both named and default exports?
- No, only one type
- Yes, both together
- Only named
- Only default
Show answer
Yes, both together — Correct! A module can have both named and default exports.
-
Match the export/import types
- named export
- by name
- default export
- one per module
- named import
- with { }
- default import
- no name needed