- JavaScript
- Modern JavaScript: ES Modules, Iterators, and Weak Collections
- JavaScript Modules (ESM vs CommonJS)
JavaScript Modules: ESM vs CommonJS & Live Bindings
In JavaScript, ES Modules use live bindings where imported identifiers reflect runtime changes in the exporting module, whereas CommonJS copies primitive values into module.exports. ESM is statically analyzable, enabling dead code elimination (tree-shaking) during bundler optimization.
Key Learning Objectives
Differentiate ECMAScript Modules (ESM) from CommonJS (CJS) in loading, parsing, and execution.
Master ESM live bindings: how exported variables maintain real-time references to module state.
Understand CommonJS value copying and why mutating an exported primitive does not update consumers.
Distinguish static import statements from dynamic import() promises and tree-shaking implications.
The Interview Problem
What is printed to the console when the following code executes, and how does the live binding model of ES Modules contrast with CommonJS value exports?
1const esmExport = (() => {2 let counter = 10;3 return {4 get counter() {5 return counter;6 },7 increment() {8 counter += 5;9 },10 };11})();1213const cjsExport = (() => {14 let counter = 10;15 return {16 counter,17 increment() {18 counter += 5;19 },20 };21})();2223const beforeESM = esmExport.counter;24const beforeCJS = cjsExport.counter;2526esmExport.increment();27cjsExport.increment();2829const afterESM = esmExport.counter;30const afterCJS = cjsExport.counter;3132console.log(beforeESM, beforeCJS, afterESM, afterCJS);
Predict Console Output
Select the option that matches what this code prints to the console:
10 10 15 10
10 10 15 15
10 10 10 10
15 15 15 15
V8 Engine Execution Trace
Step 1 of 7 (Line 1)esmExport simulation initializes module scope with counter = 10. In ESM, exports are live bindings to the module Environment Record (simulated here via a getter).
JavaScript Modules Explained
ESM vs CommonJS: Core Architectural Differences
| Feature | ECMAScript Modules (ESM) | CommonJS (CJS) |
|---|---|---|
| Export Semantics | Live bindings (real-time read-only pointers) | Value copies (shallow snapshot on module.exports) |
| Loading | Asynchronous, 3-phase (Parse -> Instantiate -> Evaluate) | Synchronous at runtime (require() blocks execution) |
| Static Analysis | Top-level import is statically analyzable -> Tree-shaking | Dynamic (require() can be called conditionally in functions) |
| Scope & Strict Mode | Module scope, strictly 'use strict' by default, top-level this is undefined | Function wrapper (exports, require, module, __filename, __dirname), top-level this is exports |
| Circular Dependencies | Supported via live bindings and uninitialized TDZ slots | Handled via partial export snapshots (can return incomplete objects) |
The 3-Phase ESM Lifecycle
- Construction (Parsing): Finds all
importdeclarations and builds the Module Record dependency graph. - Instantiation: Allocates memory space for all exported and imported bindings in module Environment Records without running code yet (linking).
- Evaluation: Executes top-level code in post-order traversal to populate the allocated memory boxes.
Common Traps & Mistakes
Attempting to reassign an imported binding in ESM (`import { count } from './mod'; count = 5`), which throws `TypeError: Assignment to constant variable` (imported bindings are immutable read-only views).
Using dynamic conditional imports with static `import` syntax: `if (condition) import foo from 'bar'` is a syntax error. Use `const foo = await import('bar')` instead.
Confusing Node.js `require()` synchronous behavior with browser ES module asynchronous script tags (`<script type="module">`), which defer execution until DOM parsing finishes.
FAANG Follow-Up Probes
Probe #1
How do circular dependencies behave in CommonJS versus ES Modules when a module accesses an imported variable before the dependency finishes executing?
Probe #2
Why can bundlers like Rollup and Webpack reliably tree-shake ES Modules but struggle to tree-shake CommonJS modules?
Probe #3
What is the 'dual package hazard' in npm libraries shipping both ESM and CommonJS builds, and how does package.json 'exports' field resolve it?
JavaScript Modules Interview Questions
Key interview inquiries, edge cases, and architectural follow-ups for JavaScript Modules (ESM vs CommonJS).
What are live bindings in ES Modules?
In ESM, an imported variable is a live reference pointing directly to the exporting module's environment record. If the exporting module mutates the variable, the imported identifier reflects the update immediately.
Why does ESM enable tree-shaking while traditional CommonJS cannot?
Because ESM import and export statements must appear at top-level with static string specifiers, bundlers can build a complete dependency graph and safely eliminate unused exports before runtime.
How does dynamic import() differ from static import declarations?
Static import is evaluated during module loading before execution. Dynamic import(modulePath) returns a Promise that loads the module on demand at runtime, enabling route-level code splitting.
How do circular dependencies behave in ESM vs CommonJS?
In CommonJS, a circular require returns a partially executed module.exports object. In ESM, live bindings allow functions and variables to resolve, though accessing uninitialized let/const bindings will trigger the TDZ.
Why does top-level this evaluate to undefined in an ES Module?
ES Modules are automatically executed in strict mode ("use strict") by specification. At top-level module scope, this is undefined rather than pointing to the global window object.
More JavaScript interview questions for freshers
