ES Modules
import and export — split code across files and manage dependencies
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
(ESM) let you split JavaScript code across files, exporting from one and importing into another.
Named exports:
javascript // math.js export const PI = 3.14159; export function add(a, b) { return a + b; } export function square(x) { return x * x; }
Named imports:
javascript import { add, PI } from './math.js'; import { add as sum } from './math.js'; // rename
Default export — one per file: ``javascript // logger.js export default function log(msg) { console.log(msg); }
Default import — any name you like: ``javascript import log from './logger.js'; import myLog from './logger.js'; // same thing, different name
Import everything:
javascript import * as Math from './math.js'; Math.add(2, 3);
Re-exporting:
javascript export { add, square } from './math.js'; export { default as log } from './logger.js';
ESM is static (imports resolved at parse time), enabling tree-shaking by bundlers like Webpack/Vite.
Examples
Named vs default exports
A file can have both named exports and one default export
// utils.js
export const VERSION = '1.0'; // named
export function clamp(n, min, max) { // named
return Math.min(Math.max(n, min), max);
}
export default class EventBus { /*...*/ } // default
// app.js
import EventBus, { VERSION, clamp } from './utils.js';Index barrel file pattern
Barrel files re-export multiple modules for a clean public API
// components/index.js
export { default as Button } from './Button.js';
export { default as Input } from './Input.js';
export { default as Modal } from './Modal.js';
// app.js — clean imports from one place
import { Button, Input, Modal } from './components';How well did you understand this?
Next in JavaScript Core
DOM Basics