Sub topic 11
The Module Pattern and IIFEs
This chapter assumes you know how closures create private state (covered in the previous chapters on private state and factory functions). You should also be comfortable with function expressions and object literals.
A factory function can be called many times, and each call builds a new object. Sometimes you need exactly one instance instead, such as a single logger, a config store, or an app-wide counter. The module pattern does this by running a function once, right away, and keeping only the public interface it returns.
Immediately Invoked Function Expressions
An IIFE (immediately invoked function expression) is a function expression that is called as soon as it is defined.
(function () {
const message = 'runs once';
console.log(message);
})();
console.log(typeof message); // 'undefined'The outer parentheses make the parser read function as an expression instead of a declaration. The trailing () calls it. Variables declared inside, such as message, live in the function's scope and never reach the global scope.
Building a Module
The module pattern combines an IIFE with a closure. The IIFE returns an object whose methods close over private variables.
const counterModule = (function () {
let count = 0;
function increment() {
count += 1;
return count;
}
function reset() {
count = 0;
}
return { increment, reset };
})();
console.log(counterModule.increment()); // 1
console.log(counterModule.increment()); // 2
counterModule.reset();
console.log(counterModule.increment()); // 1
console.log(counterModule.count); // undefinedThe IIFE finishes running at once, but its lexical environment stays alive because increment and reset still refer to count. Outside code can only reach count through those methods.
Writing every function as a private name and then listing the public ones in the return object is often called the revealing module pattern. With it, you can see the whole public API in one place.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| `function () { ... }();` | SyntaxError: the parser expects a declaration with a name | Wrap the function in parentheses |
| Forgetting the final `()` | `counterModule` holds the function, not the API object | Add `()` to call it |
| Previous line has no semicolon | `a = b` followed by `(function...)` becomes `b(function...)` | End the previous statement with `;` or start the IIFE with `;` |
| Returning `count` directly | The object gets a copy of the number, which goes stale | Return a getter function such as `getCount` |
IIFEs and ES Modules Today
Native ES modules (import/export) give each file its own scope, so top-level variables in a module are already private. That removes the main reason IIFEs were used in browser scripts. You will still see the pattern in older codebases, in bundler output, and in plain <script> files where you want to avoid adding globals.
Exercise
Write a module idGenerator using an IIFE. It should expose next(), which returns 1, 2, 3, and so on, and peek(), which returns the last issued id without changing it. The current id must not be reachable from outside.
Show answer
const idGenerator = (function () { let lastId = 0; function next() { lastId += 1; return lastId; } function peek() { return lastId; } return { next, peek }; })(); idGenerator.next(); // 1 idGenerator.next(); // 2 idGenerator.peek(); // 2 idGenerator.lastId; // undefined
Exercise
Why does const api = (function () { let n = 5; return { n }; })(); fail to give live access to n?
Show answer
The object literal { n } copies the value 5 into a property when the IIFE runs. The property is not linked to the variable, so later changes to n inside the closure are not reflected. Exposing a function like getN() { return n; } reads the variable through the closure instead.