DevPath · Learn to code ESPTEN

Modern JavaScript (ES6+)

Modules: import and export

JavaScript modules

As a program grows, it's a good idea to split it into separate files. Modules allow one file to share (export) code and another to use it (import).

Exporting

// file: math.js
export function add(a, b) {
  return a + b;
}
export const PI = 3.1416;

There is also the default export (one main export per file):

// file: greeting.js
export default function greet(name) {
  return "Hello, " + name;
}

Importing

// file: app.js
import { add, PI } from "./math.js"; // named (with braces)
import greet from "./greeting.js";   // default (without braces)

console.log(add(2, 3)); // 5
console.log(greet("Ana"));

Why do they matter?

This lesson is conceptual: modules need several real files, so here you'll only see the syntax. It's the foundation of any modern project!

Examples

How the code would look (not runnable here)

// This illustrates the syntax; there are no other files in the editor.
function add(a, b) {
  return a + b;
}
// In a real project: export function add(a, b) { ... }
console.log(add(2, 3)); // 5
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Optional chaining and nullish coalescingView the module →