JavaScript · Modules · Senior · Debugging
What happens with circular dependencies in ESM, and how do you fix them?
Short Interview Answer
ESM allows cycles with live bindings, but you may read `undefined` before initialization finishes; fix by breaking cycles or deferring access.
Detailed Explanation
If module A imports B while B imports A, exports exist as live bindings but may be uninitialized when accessed during evaluation — TDZ-like surprises for `let`/`const` exports. Symptoms: undefined functions at startup. Fixes: extract shared code to a third module, inject dependencies, convert to functions that look up later, or redesign APIs. Bundlers may warn. Treat cycles as design smells in domain layers.
Example
// a.js
import { b } from './b.js';
export function a() { return b(); }
// better: move shared helper to c.jsInterview Tip
Describe live bindings vs CJS partial exports briefly.
Common Mistake
Ignoring cycle warnings until production runtime crashes.