JavaScript · Modules · Fresh / Intern · Comparison
What are the key differences between ES modules and CommonJS?
Short Interview Answer
ESM is static and asynchronous-friendly with `import`/`export`; CommonJS uses sync `require`/`module.exports` and is still common in Node legacy code.
Detailed Explanation
ESM: static structure enables tree-shaking, top-level await (in modules), strict mode by default, and live live-bindings for exports. CJS: dynamic `require`, copies of exported values for primitives, sync loading. Node interop can be tricky (`createRequire`, dual packages). Browsers natively support ESM via `type="module"`. Prefer ESM for new code; understand CJS for ecosystem maintenance.
Example
// ESM
export function add(a, b) { return a + b; }
import { add } from './math.js';
// CJS
module.exports.add = (a, b) => a + b;
const { add } = require('./math');Interview Tip
Mention tree-shaking as a practical ESM benefit.
Common Mistake
Assuming `require` works in browser scripts without a bundler.