Course contentsShow
← JavaScript
Lesson 531 of 2,72313. ClosuresFree lesson

The Module Pattern Memory Trade-off

Why module pattern closures retain private state and when that becomes a concern.

The Module Pattern Memory Trade-off

You'll learn: Why using closures to create private state in modules can increase memory usage, and when it matters.

The Hidden Cost of Privacy

When you use the module pattern, each instance creates its own closure containing all private variables and private functions. This means every single instance carries its own copy of those functions in memory—not just the data, but the actual function definitions.

Think of it like photocopying a manual for every employee instead of giving them access to one shared manual. The privacy is convenient, but you're using more storage space.

The Trade-off in Action

// Every counter instance has its own increment function copy
function createCounter() {
  let count = 0;
  return {
    increment: function() { count++; },  // New function per instance
    getCount: function() { return count; }  // New function per instance
  };
}

const counter1 = createCounter();
const counter2 = createCounter();
// Two separate increment functions exist in memory

Compare this to prototypes (which you'll learn later), where methods are shared across all instances—only the data differs.

When Does It Matter?

For a few dozen objects, the overhead is negligible. But if you're creating thousands of instances (game entities, data records, real-time updates), the memory cost adds up. Each closure also keeps its entire scope chain alive, potentially retaining more memory than you intended.

The module pattern is fantastic for singletons or small numbers of instances where encapsulation matters more than memory efficiency.

Key Takeaway: The module pattern trades memory efficiency for privacy—every instance duplicates private functions, which is fine for a few objects but can become costly with thousands of instances.