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

Modules Are Singletons

Understand that modules are evaluated once and the same instance is shared across all imports.

Modules Are Singletons

You'll learn: How JavaScript ensures a module is only executed once, with all imports sharing the same instance.

The Core Concept

When you import a module in JavaScript, the code inside that module runs only once, no matter how many times or from how many different files you import it. Every import statement that references the same module receives the exact same instance — the same exported values, the same memory location, the same object references.

Think of a module like a restaurant's kitchen. No matter how many waiters (importers) come to get food from the kitchen, there's only one kitchen preparing the meals. They all get food from the same place, not from separate duplicate kitchens.

Why This Matters

This singleton behavior has important implications:

State is shared: If a module maintains internal state (like a counter or cached data), that state is shared across all imports. Change it in one place, and the change is visible everywhere.

Initialization runs once: Any setup code at the top level of a module executes only on the first import. Subsequent imports skip the initialization and immediately receive the already-initialized module.

Performance benefit: The browser or runtime doesn't re-parse, re-evaluate, or re-execute module code unnecessarily.

Practical Impact

When moduleA.js and moduleB.js both import utils.js, they both get the same utils.js instance. If utils.js exports an object, both modules reference the same object in memory. Modify that object from one module, and the other sees the changes.

Key Takeaway: Modules are singletons — they execute once and the same instance is shared across all imports, making state and initialization persistent throughout your application.