Course contentsShow
← JavaScript
Lesson 1430 of 2,72331. ModulesFree lesson

What is the Module Cache?

Understanding how JavaScript engines cache modules to ensure they execute only once per runtime.

What is the Module Cache?

You'll learn how JavaScript ensures a module executes only once, no matter how many times it's imported.

The Core Idea

When you import a module in JavaScript, the engine doesn't re-execute that module's code every time you import it. Instead, after the first import, JavaScript stores the module's exports in a module cache. Every subsequent import of that same module retrieves the already-executed result from this cache.

Think of it like a library book checkout system: the first person who requests a book triggers the librarian to fetch it from storage. After that, the book stays at the front desk, and anyone else who asks for it gets handed the same physical copy instantly—no need to go back to storage.

Why This Matters

Without the module cache, importing the same module multiple times would:

  • Re-execute all the module code each time
  • Create multiple instances of exported objects
  • Waste performance on redundant operations

The cache ensures modules are singletons per runtime—there's only one instance of each module's state, shared across all imports.

How It Works

  1. You import a module for the first time
  2. JavaScript fetches, parses, and executes it
  3. The engine stores the module's exports in an internal cache (keyed by module path)
  4. Future imports of that same path return the cached exports immediately
  5. The module code never runs again in that runtime

This behavior is automatic and invisible to you—there's no API to access or clear the cache manually in standard JavaScript.

Key Takeaway: JavaScript's module cache ensures each module executes only once per runtime, storing its exports for instant reuse across all imports, guaranteeing singleton behavior and optimal performance.