Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Modules (import / export) — JavaScript interview guide

15 / 23Language EssentialsMedium priorityEasy 15 min

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

Creation phaseStep 1/8
app.js
▶import { add } from "./math.js";
2
3console.log("app starts");
4console.log(add(2, 3));
5
6button.onclick = async () => {
7 const { drawChart } = await import("./chart.js");
8 drawChart();
9};
Call Stack
last in, first out

empty — event loop can run

Memory / Scope

empty

Web APIs (browser)
runs outside JS
download math.js
Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

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

  1. Lazy-load a heavy component with dynamic import.

Keep learning