Sub topic 11
The Module Pattern and IIFEs
This chapter assumes you are comfortable with function expressions, with the difference between var and let/const, and with the private state pattern from the earlier chapters, where a function returns methods that close over local variables. In that pattern you call the outer function whenever you want a new instance. The module pattern covers the case where you want exactly one instance, created once, with private internals and a public interface. The tool it uses is the immediately invoked function expression, or IIFE.
What an IIFE Is
An IIFE is a function expression that is called right where it is defined. It runs once, and its local variables live in a scope that no outside code can name.
(function () {
const secret = 'hidden';
console.log('IIFE ran, secret is', secret);
})();
console.log(typeof secret); // 'undefined'The syntax has two parts:
- The function sits inside parentheses
( ... ), which makes the parser read it as an expression instead of a function declaration. - The trailing
()calls that expression immediately.
The parentheses are required. A statement that begins with the keyword function is parsed as a declaration, and you cannot call a declaration in place:
// SyntaxError: Function statements require a function name
// function () { console.log('nope'); }();Even if you give the function a name, function f() {}() is still a syntax error, because the parser treats the trailing () as an empty grouping expression, which is not allowed.
Syntax Variants
These forms all do the same thing. You will see each of them in real code.
(function () { console.log('a'); })(); // call outside the parens
(function () { console.log('b'); }()); // call inside the parens
(() => { console.log('c'); })(); // arrow function IIFE
!function () { console.log('d'); }(); // unary operator forces an expression
void function () { console.log('e'); }(); // same idea, result discardedAn arrow IIFE must use the first form, (() => {...})(). Writing (() => {...}()) is a syntax error because an arrow function cannot be called before the parentheses around it close.
An IIFE can also take arguments, which is how modules declare their dependencies:
const greeting = (function (name, punctuation) {
return 'Hello, ' + name + punctuation;
})('Ada', '!');
console.log(greeting); // 'Hello, Ada!'Why IIFEs Existed
Before ES2015, JavaScript had no let, no const, and no native modules. Every var declared at the top level of a script became a property of the global object, and all scripts on a page shared that one global scope. Two libraries that both declared var config would overwrite each other without any warning.
Function scope was the only kind of private scope available. Wrapping a whole file in an IIFE put all of its variables into a function scope and left the global scope untouched. This is why so much older library code begins with (function () { and ends with })();.
The Module Pattern
The module pattern combines an IIFE with a returned object. The IIFE runs once and creates one lexical environment. The returned object's methods close over that environment, so they can keep using its variables after the IIFE has returned.
const counterModule = (function () {
let count = 0;
function increment() {
count += 1;
return count;
}
return { increment };
})();
console.log(counterModule.increment()); // 1
console.log(counterModule.increment()); // 2
console.log(counterModule.count); // undefinedcount cannot be reached from outside. The only way to change it is through increment. Because the IIFE runs exactly once, counterModule is a singleton: there is one count for the whole program, unlike a factory function, which creates a fresh environment on every call.
The Revealing Module Pattern
A common variant defines every function as a private local and then "reveals" chosen ones at the end. The public interface is listed in one place, and public methods can call private helpers by plain name.
const cart = (function () {
const items = [];
function validate(item) {
return typeof item.price === 'number' && item.price >= 0;
}
function add(item) {
if (!validate(item)) {
throw new Error('Invalid item');
}
items.push(item);
}
function total() {
return items.reduce((sum, item) => sum + item.price, 0);
}
return { add, total };
})();
cart.add({ name: 'pen', price: 2 });
cart.add({ name: 'book', price: 15 });
console.log(cart.total()); // 17
console.log(typeof cart.validate); // 'undefined'Importing Dependencies Through Parameters
Modules often receive their dependencies as IIFE arguments instead of reading globals by name. The dependency is visible at the top of the file, and inside the module it gets a short local name.
const logger = {
log(message) { console.log('[log]', message); }
};
const userService = (function (log) {
const users = new Map();
function addUser(id, name) {
users.set(id, name);
log.log('Added ' + name);
}
function getUser(id) {
return users.get(id);
}
return { addUser, getUser };
})(logger);
userService.addUser(1, 'Grace'); // [log] Added Grace
console.log(userService.getUser(1)); // 'Grace'Common Errors
Missing Semicolon Before an IIFE
When automatic semicolon insertion (ASI) does not add a semicolon, a line that starts with ( continues the previous line. ASI is the rule that inserts semicolons where you left them out.
const base = 1
(function () {
console.log('never runs');
})();
// TypeError: 1 is not a functionThe parser reads this as const base = 1(function () {...})(). That is why some libraries start their files with ;(function () {: the leading semicolon protects the IIFE when files are joined together.
Exposing a Primitive Instead of a Live Value
Putting a private variable directly on the returned object copies its value at return time. Later changes to the variable do not show up.
const broken = (function () {
let count = 0;
return {
count,
increment() { count += 1; }
};
})();
broken.increment();
console.log(broken.count); // 0, the copy never changesThe closure captures the variable count, but the property count on the object is a separate copy that took the value 0 once. To expose a live value, read it through a function or a getter:
const fixed = (function () {
let count = 0;
return {
get count() { return count; },
increment() { count += 1; }
};
})();
fixed.increment();
console.log(fixed.count); // 1The getter also makes the property read-only from outside. Assigning fixed.count = 99 has no effect on the private variable, and in strict mode it throws a TypeError.
Expecting `this` to Be the Module
Inside a plain IIFE, this is undefined in strict mode and the global object otherwise. It is never the returned object. Methods that use this work only when they are called as module.method(), and they break when detached, for example const inc = module.increment. Methods that refer to closed-over variables by name, as in the examples above, keep working however they are called.
IIFE Modules Versus ES Modules
ES modules (import/export) give each file its own scope, so most new code does not need IIFEs for privacy. The closure idea is the same: an exported function can still use the module's top-level variables that are not exported.
| Aspect | IIFE module pattern | ES modules |
|---|---|---|
| Privacy mechanism | Function scope plus closure | File-level module scope |
| Dependencies | IIFE arguments or globals | `import` statements |
| Instances | One per IIFE run (singleton) | One per module specifier (singleton) |
| Exported bindings | Copies unless exposed through functions or getters | Live bindings that update |
| Static analysis and tree shaking | Not possible | Supported by bundlers |
| Works without a build step in old browsers | Yes | No |
You will still meet IIFEs in older code, in UMD library bundles, in bundler output, and for short one-off jobs, such as running top-level await logic in environments that do not support it:
(async () => {
const value = await Promise.resolve(42);
console.log(value); // 42
})();Exercise
What does this code print, and why? const m = (function () { let n = 10; return { n, bump() { n += 1; return n; } }; })(); m.bump(); console.log(m.n, m.bump());
Show answer
It prints 10 12. The property m.n was copied from n once, when the object was created, so it stays 10. The private variable n becomes 11 after the first bump() and 12 after the second, and the second call's return value is what gets logged.
Exercise
Write a module named idGenerator, built with an IIFE, that exposes next() (returns 1, 2, 3, ... on successive calls) and reset() (makes the next call return 1 again). The current counter must not be readable or writable from outside.
Show answer
const idGenerator = (function () { let current = 0; return { next() { current += 1; return current; }, reset() { current = 0; } }; })(); Here current lives only in the IIFE's lexical environment, and next and reset reach it through their closures.
Exercise
A file contains const total = compute() on one line and (function () { setup(); })() on the next, with no semicolons. What happens, and what are two ways to fix it?
Show answer
ASI inserts no semicolon, so the code is parsed as compute()(function () { setup(); })(). It tries to call the return value of compute() as a function, which usually throws a TypeError. Fix it by ending the first line with a semicolon, or by starting the IIFE line with one: ;(function () { setup(); })().