Factory Function
noun
say it: “FAK-tuh-ree FUNGK-shun” /ˈfæktəri ˈfʌŋkʃən/
A plain function that builds and returns a new object each time you call it, often keeping that object's private data in a closure.
What is Factory Function in JavaScript?
Factory Function — A plain function that makes and returns a new object each time it's called, like a machine that stamps out game counters. A variable it declares stays private to each object it made, kept alive by a closure.
function makeLivesCounter(start) {
let lives = start;
return {
loseOne: () => (lives -= 1),
check: () => lives,
};
}
const player = makeLivesCounter(3);
player.loseOne();
console.log(player.check()); // 2
In a sentence
- “I called the factory function makeCounter twice and got two counters that keep separate counts.”
Level: Journeyman · More JavaScript terms at this level
Updated