Module lessons (1/4)
ESM modules: import / export
When a program grows, keeping everything in a single file becomes awkward. Modern JavaScript solves the problem with ES modules (ESM): each file is a module that can export functions, constants, classes, and other files can import them.
export
You export what you want to make public. Two forms:
// somma.js
export function somma(a, b) {
return a + b;
}
export const PI = 3.14159;Or, at the end of the file:
function somma(a, b) {
return a + b;
}
const PI = 3.14159;
export { somma, PI };import
From another file:
// app.js
import { somma, PI } from './somma.js';
console.log(somma(1, 2)); // 3
console.log(PI); // 3.14159The object { somma, PI } is the list of names you want to import. They must match the
exported names.
Default export
Each module can have one "main" export, without a name:
// log.js
export default function log(msg) {
console.log('[app]', msg);
}You import it by choosing the name locally:
import log from './log.js';
log('ciao');Renaming
import { somma as plus } from './somma.js';
export { somma as add } from './somma.js'; // re-exportOne "namespace" per file
Modules are isolated: a variable declared in a file does not end up in the global scope. You
have to export it explicitly to make it visible elsewhere. This is a huge improvement over
old-school JS where every <script> shared window.
Try it
In the exercises below you will not write real import/export syntax — the sandbox is a single
file. Instead, we will ask you to organize the code into small separate functions that
collaborate, as you would if each were in a different file.
Define two separate functions: `square(n)` (returns n*n) and `sumOfSquares(a, b)` that uses square. Think of square as 'exported' from a file and reused by sumOfSquares.
Show hint
sumOfSquares(a,b) = square(a) + square(b)
Solution available after 3 attempts
Review exercise
Define `isEven(n)` (true if n is even) and `countEven(arr)` that uses isEven to count even elements in an array. Keep them as two separate functions.
Show hint
arr.filter(isEven).length
Solution available after 3 attempts