Cache Implications for Circular Dependencies
You'll learn how JavaScript's module cache prevents infinite loops when two modules import each other, but at the cost of receiving partially-initialized modules.
The Core Problem
When Module A imports Module B, and Module B imports Module A, you have a circular dependency. Without the module cache, this would cause an infinite loop: A loads B, B loads A, A loads B, and so on forever.
The module cache saves the day by breaking this cycle. When JavaScript starts loading a module, it immediately places a placeholder entry in the cache—even before the module finishes executing. If another module requests it during that loading process, JavaScript returns whatever has been initialized so far.
How It Works
Imagine two friends simultaneously writing each other's phone numbers. Person A starts writing, and Person B asks "What's your number?" Person A can only share the digits written so far—the rest are still blank. That's exactly what happens with circular imports.
// fileA.js
import { b } from './fileB.js';
export const a = 'Module A';
console.log('A sees B:', b);
// fileB.js
import { a } from './fileA.js';
export const b = 'Module B';
console.log('B sees A:', a); // might be undefined!
When fileA starts loading and reaches the import of fileB, JavaScript switches to loading fileB. When fileB tries to import from fileA, the cache returns fileA's exports as they exist right now—which is before a has been declared. Result: a is undefined in fileB.
The Takeaway
Key Takeaway: The module cache prevents circular dependency deadlocks by returning partially-initialized modules, which means imported values may be undefined if accessed before their declaration executes—circular dependencies work, but require careful ordering of exports.