Skip to main content
eLearner.app
Module 8 · Lesson 1 of 429/32 in the course~12 min
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:

JS
// somma.js
export function somma(a, b) {
  return a + b;
}

export const PI = 3.14159;

Or, at the end of the file:

JS
function somma(a, b) {
  return a + b;
}
const PI = 3.14159;
export { somma, PI };

import

From another file:

JS
// app.js
import { somma, PI } from './somma.js';

console.log(somma(1, 2)); // 3
console.log(PI); // 3.14159

The 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:

JS
// log.js
export default function log(msg) {
  console.log('[app]', msg);
}

You import it by choosing the name locally:

JS
import log from './log.js';
log('ciao');

Renaming

JS
import { somma as plus } from './somma.js';
export { somma as add } from './somma.js'; // re-export

One "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.

Exercise#js.m8.l1.e1
Attempts: 0Loading…

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.

Loading editor…
Show hint

sumOfSquares(a,b) = square(a) + square(b)

Solution available after 3 attempts

Review exercise

Exercise#js.m8.l1.e2
Attempts: 0Loading…

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.

Loading editor…
Show hint

arr.filter(isEven).length

Solution available after 3 attempts