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?
- Organization: each file has a clear responsibility.
- Reusability: you import the same thing from several places.
- Encapsulation: only what you explicitly export is shared.
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