Modules (import / export) — JavaScript interview guide
Modules (import / export)
ES modules split code into files with import and export. Dynamic import() loads code only when needed, which is the base of code splitting.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Static imports load first, import() loads on demand
▶import { add } from "./math.js";23console.log("app starts");4console.log(add(2, 3));56button.onclick = async () => {7const { drawChart } = await import("./chart.js");8drawChart();9};
empty — event loop can run
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
nothing printed yet
What happens:Before ANY line of app.js runs, the browser reads all static import lines and downloads those files. That is why imports must be at the top.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Named vs default
A file can have many named exports and one default export.
// math.js
export const add = (a, b) => a + b;
export default function multiply(a, b) { return a * b; }
// app.js
import multiply, { add } from "./math.js";
// load on demand
const { Chart } = await import("./chart.js");ES modules vs CommonJS
ESM (import/export) is static, async and tree-shakeable. CommonJS (require/module.exports) is synchronous and mostly used in older Node.js code.
Remember this
- Modules run in strict mode by default.
- Each module runs only once, even if imported many times.
- Static imports enable tree shaking.
Interview questions
What is tree shaking?
The bundler removes exports that are never imported. It works because ES module imports are static and known at build time.
Practice
- Lazy-load a heavy component with dynamic import.