🟑 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