What is the Factory pattern?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A factory is a function that creates and returns objects, so callers do not have to know which concrete type they are getting or how it is built.
function createNotifier(type) {
switch (type) {
case "email": return { send: (msg) => sendEmail(msg) };
case "sms": return { send: (msg) => sendSms(msg) };
default: return { send: (msg) => console.log(msg) };
}
}
createNotifier(userPreference).send("Order shipped");
The caller works with one interface — send — and the decision about which implementation to use is made in one place.
In JavaScript, a factory is often just a function
You do not need classes or a registry. A plain function returning an object literal is the idiomatic form, and it has two advantages over a constructor: no new to forget, and closures give you genuinely private state.
function createCounter(start = 0) {
let count = start; // private, no #fields needed
return {
increment: () => ++count,
get value() { return count; },
};
}
Factory vs class
A class puts methods on the prototype — one shared copy, cheaper at scale, and you get instanceof and extends. A factory creates new function objects per call, costing memory, but avoids this entirely and cannot be called incorrectly.
Use a class when you need inheritance or many instances; a factory when you want privacy, want to return different shapes, or want to decide the type at runtime.
Where you have seen it
document.createElement(tag) is a factory — one call returns a different class depending on the argument. So are createStore, createClient and most createSomething functions in libraries.
The caution
A factory whose switch keeps growing is a sign to move to a lookup table, so adding a type means adding an entry rather than editing the function.
