JavaScript › ES Modules

Why can circular module imports (Module A imports B, which imports A) cause subtle bugs?

Advanced

Answer

Because of live bindings and evaluation order, one of the two modules will see an export from the other as undefined (or an incomplete value) at the moment its own top-level code runs, since the other module hasn't finished executing yet — the value often becomes correct only later, after both modules finish loading.
// a.js
import { b } from './b.js';
console.log(b); // may log undefined here
export const a = 'A';

// b.js
import { a } from './a.js';
export const b = 'B';
Real-world example Debugging a mysterious 'undefined is not a function' error caused by two modules that import each other.

Common follow-ups: How do you refactor code to break a circular dependency?