JavaScript Course
JavaScript
/
Intermediate

Module Pattern

Definition

A design pattern used to emulate the concept of classes and true encapsulation (private variables) in JavaScript using Closures and IIFEs.

Explain Like I'm New

Before modern JavaScript had the `import/export` syntax, everything was global. The Module Pattern was a clever trick to put your variables in a hidden box, and only cut a small hole in the box to let specific functions (the public API) out.

Real World Example

Creating a Shopping Cart where the `items` array is completely hidden from the rest of the application. The only way to interact with it is via the exposed `addItem()` and `getTotal()` methods.

Common Use Cases

  • •Encapsulation
  • •Data Privacy
  • •Legacy codebase architecture

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is Encapsulation?

intermediate

  • How does the Module Pattern achieve privacy?

advanced

  • Is the Module Pattern still necessary with ES6 Modules?

Flash Cards

Question

How does it achieve privacy?

Click to reveal answer
Answer

It relies entirely on Closures. By defining an array inside a function, and then returning an object containing methods that reference that array, the array is kept alive in memory. But because the array itself wasn't returned, no outside code can possibly touch it directly.

Question

Is it still necessary with ES6 Modules?

Click to reveal answer
Answer

Mostly no. ES6 modules provide file-level scope. If you declare a variable inside `cart.js` but don't `export` it, it is perfectly private. The modern language has solved the problem the pattern was invented to fix.