In JavaScript, the factory pattern usually means a factory function: a function that creates and returns an object so callers do not wire up every property themselves. Searchers use phrases like factory pattern javascript, javascript factory pattern, js factory pattern, and factory method javascript for the same idea at different levels (plain objects, new, or class-based creators).
This page shows small, runnable patterns. Every text block is exact output from Node.js v20.18.2 on Linux for the matching script.
Simple factory (object literals)
function createObject(type) {
let obj;
if (type === "go") {
obj = {
prop1: "value1",
prop2: "value2",
goMethOne: function () {
console.log("This is go method 1");
},
goMethTwo: function () {
console.log("This is go method 2");
},
};
} else if (type === "linux") {
obj = {
prop1: "value1",
prop2: "value2",
linuxMethOne: function () {
console.log("This is linux method 1");
},
linuxMethTwo: function () {
console.log("This is linux method 3");
},
};
}
return obj;
}
const objA = createObject("go");
console.log(require("util").inspect(objA, { depth: 1, colors: false }));{
prop1: 'value1',
prop2: 'value2',
goMethOne: [Function: goMethOne],
goMethTwo: [Function: goMethTwo]
}The factory centralizes which shape to return for a type string.
Factory with constructors (new)
function Go() {
this.prop1 = "value1";
this.prop2 = "value2";
}
Go.prototype.method1 = function () {
console.log("This is Go method 1");
};
Go.prototype.method2 = function () {
console.log("This is Go method 2");
};
function Linux() {
this.prop1 = "value1";
this.prop2 = "value2";
}
Linux.prototype.method1 = function () {
console.log("This is Linux method 1");
};
Linux.prototype.method2 = function () {
console.log("This is Linux method 2");
};
function createObject(type) {
let obj;
if (type === "Go") {
obj = new Go();
} else if (type === "Linux") {
obj = new Linux();
}
return obj;
}
console.log(createObject("Linux"));Linux { prop1: 'value1', prop2: 'value2' }Here the factory chooses the constructor; shared behavior lives on prototype. For class syntax and inheritance, see the JavaScript classes guide on this site.
Factory methods on ES6 classes (self-contained)
class SUV {
constructor(make, model, year, color, features) {
Object.assign(this, { make, model, year, color, features });
}
}
class Sedan {
constructor(make, model, year, color, features) {
Object.assign(this, { make, model, year, color, features });
}
}
class CarFactory {
createSUV() {
return new SUV("Toyota", "RAV4", "2021", "white", [
"4WD",
"backup camera",
"Bluetooth",
]);
}
createSedan() {
return new Sedan("Honda", "Civic", "2022", "blue", [
"Apple CarPlay",
"blind spot monitoring",
"sunroof",
]);
}
}
const factory = new CarFactory();
console.log(factory.createSUV());SUV {
make: 'Toyota',
model: 'RAV4',
year: '2021',
color: 'white',
features: [ '4WD', 'backup camera', 'Bluetooth' ]
}This is the usual “factory method” style in modern JavaScript: methods on a CarFactory class encapsulate new SUV() / new Sedan() details.
Closure factory (private state)
A JavaScript function factory can hide variables in a closure—useful for per-instance private fields without # private class fields.
function createCounter(start) {
let n = start;
return {
next() {
return ++n;
},
peek() {
return n;
},
};
}
const c = createCounter(10);
console.log(String(c.peek()) + " " + String(c.next()) + " " + String(c.next()));10 11 12Async factory (Promise)
const DELAY_MS = 50; // shorten wait for reproducible logs; same control flow as slower I/O
function createCarAsync(type) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
let car;
if (type === "SUV") {
car = {
make: "Toyota",
model: "RAV4",
year: "2021",
color: "white",
features: ["4WD", "backup camera", "Bluetooth"],
};
} else if (type === "sedan") {
car = {
make: "Honda",
model: "Civic",
year: "2022",
color: "blue",
features: ["Apple CarPlay", "blind spot monitoring", "sunroof"],
};
}
if (car) {
resolve(car);
} else {
reject(new Error("Invalid car type"));
}
}, DELAY_MS);
});
}
createCarAsync("SUV")
.then(function (car) {
console.log(JSON.stringify(car));
})
.catch(function (error) {
console.error(error.message);
});{"make":"Toyota","model":"RAV4","year":"2021","color":"white","features":["4WD","backup camera","Bluetooth"]}Factory vs Abstract Factory (short)
- Factory (this article): one place decides which concrete object to build (
createObject("linux"),CarFactory#createSUV). - Abstract Factory (classic): multiple factories or products grouped as families (e.g., UI kit for Windows vs macOS). In JavaScript you often approximate that with modules exporting related factories, not a single helper.
Singleton vs cached factory
A singleton exposes one global instance (see JavaScript singleton pattern). A factory normally returns a new object each call. If you cache the first result and return it forever, you are mixing singleton-like behavior with a factory—name that clearly in code comments so readers are not surprised.
Summary
The factory pattern in JavaScript is mostly about one function (or class method) that builds objects so creation rules stay in one place. Use plain object factories for flexibility, constructors or classes when you want instanceof and shared prototypes, closures for private state, and Promise-based factories when creation needs async work.
Frequently Asked Questions
1. What is a factory function in JavaScript?
A factory function is a normal function that creates and returns an object (often a plain object literal) without requiring the caller to use the new operator. You call it like createUser('Ada') and get a fresh object each time.2. What is the difference between a factory function and a JavaScript class?
A class defines a blueprint and instances are usually created with new. A factory function returns an object directly and can hide setup logic, return different shapes based on input, or use closures for private state without class fields.3. Is the JavaScript factory pattern the same as the Abstract Factory pattern?
Not exactly. A simple JS factory often picks one concrete object. Abstract Factory (classic GoF) builds families of related objects behind interfaces; you can approximate it with multiple factories or modules, but it is a larger structure.4. Does a factory function improve performance in JavaScript?
Not automatically. Plain factories that attach methods on each object duplicate function references per instance, which can cost more memory than shared prototype methods on constructors or classes.5. Can a factory return a Promise in JavaScript?
Yes. An async factory can perform I/O, then resolve to the configured object. Callers use await or then like any other Promise.6. What is a singleton factory?
It is not a standard GoF term. People sometimes mean a function that returns the same cached instance (singleton-like). That is different from a factory that returns a new object on every call.References
new operator - JavaScript | MDN
Classes - JavaScript | MDN
Factory method pattern (Wikipedia)
