Skip to content

IIFEs vs Namespaced Objects

A namespace object and an IIFE both wrap a script’s code so that it adds only one name to the global scope. The difference is privacy. Every property of a namespace object can be read and changed from outside, whereas an IIFE, an immediately invoked function expression, can keep variables inside its own scope and hand back an object that exposes only the parts other code should use.

Use a plain namespace object when everything in it is meant to be public, such as a set of formatting helpers. Use an IIFE, or in current code a module, when some state must not be changed from outside.

This counter keeps its count as a property, so any code can overwrite it.

const COUNTER = {
count: 0,
increment() {
this.count += 1;
return this.count;
},
};
COUNTER.increment();
COUNTER.count = -50;
console.log(COUNTER.increment());

This prints:

-49

Here the function runs once, straight away, and its return value is stored in COUNTER. The count variable lives in the function’s scope, and the returned functions can still reach it because they are closures over that scope. Nothing outside the function can.

const COUNTER = (() => {
let count = 0;
const increment = () => {
count += 1;
return count;
};
const reset = () => {
count = 0;
};
return { increment, reset };
})();
COUNTER.increment();
COUNTER.count = -50;
console.log(COUNTER.increment());
console.log(Object.keys(COUNTER));

This prints:

2
[ 'increment', 'reset', 'count' ]

Assigning COUNTER.count adds a new, unrelated property to the returned object, so it has no effect on the private count. This arrangement is often called the module pattern, and the object it returns is the module’s public interface.

An IIFE can hide functions as well as values. In this example, findBook and the books array are private, and the returned object offers three ways to use them, one of which is a getter.

const LIBRARY = (() => {
const books = [];
let nextId = 1;
const findBook = (id) => books.find((book) => book.id === id);
return {
add(title) {
books.push({ id: nextId, title, onLoan: false });
nextId += 1;
},
lend(id) {
const book = findBook(id);
if (!book || book.onLoan) return false;
book.onLoan = true;
return true;
},
get available() {
return books.filter((book) => !book.onLoan).map((book) => book.title);
},
};
})();
LIBRARY.add('Emma');
LIBRARY.add('Dracula');
console.log(LIBRARY.lend(1), LIBRARY.lend(1));
console.log(LIBRARY.available);
console.log(typeof LIBRARY.findBook);

This prints:

true false
[ 'Dracula' ]
undefined

The second attempt to lend book 1 fails because it is already on loan, and findBook is not reachable from outside.

Namespace object IIFE returning an object
Global names added one one
Private variables and functions none any declared inside the function
Inside the methods this or the namespace’s name plain variable names, with no this needed
Can be added to later yes, by assigning new properties only the returned object can, and new methods cannot see the private variables

ES modules have replaced both patterns for most code. A module has its own scope, so anything it does not export is private, and a module’s code runs once however many times it is imported. A counter module would declare let count = 0 at the top level and export only increment and reset. Code Structure shows modules in use.

Classes can also hold private state, in fields whose names start with #:

class Counter {
#count = 0;
increment() {
this.#count += 1;
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.increment());
console.log(Object.keys(counter));

This prints:

2
[]

The IIFE is still worth knowing, because a great deal of existing code and many older libraries are built on it.

Steve Griffith covers this topic in his video Comparing IIFEs and Namespaced Objects.