The module pattern
Learn the module pattern that protects private variables from outside.
The module pattern
The module pattern combines an IIFE with a returned object. The IIFE wraps the private state; the returned object exposes only the public API.
For example, let count = 0 stays inside the IIFE. Outside code can call counter.increment() but cannot reach count directly. The private variable is protected.
Revealing module
A variant is the revealing module pattern. You declare all helper functions normally inside the IIFE; the returned object at the end shows only the ones you want to expose.
This gathers the public surface in one place. Readability improves; private helpers stay hidden, and you can rename a method internally while keeping its outside name stable.
Exercise Write a counter module
Write a module called counter using an IIFE. Inside the IIFE keep a private let count = 0. The returned object should have increment (increments and returns the count) and get (returns the count) methods. The IIFE should be invoked as (function() { ... })().
Show example solution
const counter = (function() {
let count = 0;
return {
increment: function() { count++; return count; },
get: function() { return count; }
};
})();
Test yourself
-
Where does a private variable live in the module pattern?
- In the global scope
- Public on the returned object
- Nowhere, it is auto-deleted
- In the IIFE's closure, not accessible from outside
Show answer
In the IIFE's closure, not accessible from outside — Correct. The private variable is trapped in the IIFE's scope; it is reachable only indirectly through the returned methods.
-
Match the module concepts
- module pattern
- IIFE returning an object guards state
- private variable
- Variable hidden from outside
- public API
- Methods callable from outside
- revealing module
- Gathers exports at the end
-
Pick the right method
const counter = (function() { let count = 0; return { get: ____, increment: function() { count++; } }; })();Show answer
const counter = (function() { let count = 0; return { get: function() { return count; }, increment: function() { count++; } }; })();