Factory Functions
Create objects with private state via closures.
Factory Functions is a free JavaScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Factory Function
A factory function is any function that returns a new object. Unlike a constructor, you call it normally (no new), and it can use closures for private state.
function createUser(name) {
return {
name,
greet: () => "Hi, I am " + name
};
}
const u = createUser("Ada");
console.log(u.greet()); // "Hi, I am Ada"No new Keyword
Factories avoid the pitfalls of new and this. You simply call the function and get an object back.
function point(x, y) {
return { x, y };
}
const p = point(3, 4);
console.log(p.x, p.y); // 3 4Private State via Closure
Variables declared in the factory are private. The returned object methods close over them, just like the module pattern but producing many instances.
function createCounter() {
let count = 0; // private
return {
inc: () => ++count,
get: () => count
};
}
const c = createCounter();
c.inc();
console.log(c.get()); // 1Many Independent Instances
Each call to the factory produces a fresh object with its own private state. This is the key difference from a singleton module.
function createCounter() {
let n = 0;
return { inc: () => ++n };
}
const a = createCounter();
const b = createCounter();
console.log(a.inc(), a.inc()); // 1 2
console.log(b.inc()); // 1Computed Properties
Factories can derive values at creation time and expose computed methods, keeping the inputs private.
function rectangle(w, h) {
return {
area: () => w * h,
perimeter: () => 2 * (w + h)
};
}
const r = rectangle(3, 4);
console.log(r.area()); // 12
console.log(r.perimeter()); // 14Default and Optional Config
Because they are plain functions, factories handle defaults and options cleanly with destructuring.
function createButton({ label = "OK", disabled = false } = {}) {
return { label, disabled };
}
console.log(createButton()); // { label: "OK", disabled: false }
console.log(createButton({ label: "Go" })); // { label: "Go", disabled: false }Composition Over Inheritance
Factories favor composition: build an object by mixing in behaviors instead of extending a class chain.
const canFly = (s) => ({ fly: () => s.name + " flies" });
function createBird(name) {
const self = { name };
return Object.assign(self, canFly(self));
}
console.log(createBird("Robin").fly()); // "Robin flies"Shared Behavior
To share methods across instances without per-instance copies, define them once and assign. Or accept the small cost for the privacy benefit closures give.
const behavior = {
describe() { return "id " + this.id; }
};
function createItem(id) {
return Object.assign({ id }, behavior);
}
console.log(createItem(7).describe()); // "id 7"Returning Functions Too
A factory can return a function instead of an object when that is the cleaner interface, still capturing private state.
function multiplier(factor) {
return (n) => n * factor;
}
const triple = multiplier(3);
console.log(triple(5)); // 15Factory vs Constructor
Constructors use new, this, and the prototype chain. Factories are simpler, avoid this bugs, and give real privacy via closures, at the cost of not sharing methods on a prototype.
Validation on Creation
Factories can validate inputs and throw or normalize before returning, guaranteeing every produced object is valid.
function createAge(value) {
if (value < 0) throw new Error("age must be >= 0");
return { value };
}
console.log(createAge(30).value); // 30Quick Check
Factory functions.
Recap
Factory functions return objects without new or this, using closures for private state. Each call yields an independent instance, supporting computed properties, default config, composition, and validation. They trade prototype method sharing for simplicity and genuine privacy, making them a clean, closure-powered alternative to constructors.
Frequently asked questions
Is the “Factory Functions” lesson free?
Yes — the full text of “Factory Functions” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Factory Functions”?
Create objects with private state via closures. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Factory Functions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.