MediumModern JS📖 Theory Question

What are ES Modules and how do they differ from CommonJS?

💡

Hint

ESM: static import/export, live bindings, always strict; CJS: require(), dynamic, copied values

Full Answer

// ── ES Modules (ESM) ─────────────────────────────
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class App {}

// main.js
import { PI, add } from './math.js';   // named imports
import App from './App.js';             // default import
import * as Math from './math.js';      // namespace

// ── CommonJS (CJS) ─────────────────────────────
module.exports = { PI, add };
const { PI, add } = require('./math');

// ── Key Differences ────────────────────────────
FeatureESMCommonJS
AnalysisStatic (parse time)Dynamic (runtime)
BindingLive (tracks changes)Copied (snapshot)
Strict modeAlwaysOpt-in
Top-level await
Browsertype="module"Bundler needed
Tree shaking✅ (static)❌ (dynamic)
💡 Tree-shaking only works with ESM because imports are static — bundlers can analyze what's used. CJS require() is dynamic so bundlers can't eliminate dead code.

More Modern JS Questions

MediumWhat are generators and when would you use them?EasyWhat is optional chaining (?.) and nullish coalescing (??)?EasyWhat are tagged template literals and what are they used for?EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint