Cache Keys and Module Resolution
You'll learn how JavaScript uses absolute file paths to uniquely identify modules in its cache and prevent duplicate loading.
When you import the same module from different files, JavaScript needs to know whether it's truly the same module or a different one. The answer lies in how modules are cached.
How Cache Keys Work
JavaScript uses the absolute file path as the unique identifier (cache key) for each module. When you write a relative import like './utils.js', the module system resolves it to an absolute path first:
// In /src/app.js
import { helper } from './utils.js';
// Resolves to: /src/utils.js
// In /src/components/button.js
import { helper } from '../utils.js';
// Resolves to: /src/utils.js ← Same absolute path!
Even though the import statements look different (./ vs ../), they both resolve to the same absolute path: /src/utils.js. This means JavaScript recognizes them as the same module and returns the cached version.
Why This Matters
This resolution strategy prevents accidental duplicate loading. If cache keys were based on the relative path string instead, you could end up with multiple copies of the same module—each with its own state and execution—which would break the singleton behavior.
Think of it like a library card catalog: no matter which aisle you walk from, "JavaScript: The Definitive Guide" has one call number, one physical location, and one copy on the shelf.
Resolution Happens Before Caching
The module system always resolves imports to absolute paths before checking the cache. This ensures consistency across your entire application.
Key Takeaway: JavaScript uses absolute file paths as cache keys, so different relative paths pointing to the same file will always retrieve the same cached module instance.