Single Execution Guarantee
What you'll learn: How JavaScript's module cache ensures that a module's top-level code runs exactly once, no matter how many times you import it.
The One-Time Execution Promise
You've learned that JavaScript maintains a module cache. One of its most important jobs is guaranteeing that each module executes only once during your application's lifetime, even if you import it from multiple places.
When you first import a module, JavaScript:
- Loads the file
- Executes all its top-level code
- Stores the resulting exports in the cache
- Returns those cached exports
Every subsequent import of that same module skips steps 1-2 and jumps straight to returning the cached exports. The top-level code never runs again.
Why This Matters
Imagine a module that initializes a database connection:
// database.js
console.log('Connecting to database...');
const connection = createConnection();
export { connection };
If you import this module from five different files, you'll only see "Connecting to database..." printed once. You get the same connection object everywhere, not five separate connections. This is intentional and powerful.
The Analogy
Think of a module like a light switch in a room. The first person to enter (first import) flips the switch on (runs the code). Everyone else who enters afterward benefits from the light being on, but they don't need to flip the switch again. The room stays lit (module stays cached) for everyone.
This guarantee makes modules predictable and safe for initialization logic, configuration, and shared state.
Key Takeaway: JavaScript's module cache ensures every module's top-level code executes exactly once, no matter how many times it's imported—making modules reliable for initialization and shared resources.