See this explanation for some good reasons: https://www.reddit.com/r/javascript/s/SquoeVYzoK Answer from 1_4_1_5_9_2_6_5 on reddit.com
🌐
Reddit
reddit.com › r/javascript › [askjs] factory functions vs. constructors. why choose factory functions?
r/javascript on Reddit: [AskJS] Factory functions vs. Constructors. Why choose factory functions?
March 13, 2024 -

Hi, from my limited understanding of both concepts there are two big differences between the two. Firstly, constructors create a prototype and factory functions don't. Secondly, factory functions return an object(which can include functions). so if we return functions that reference variables we don't want a user to directly access we effectively create a private variable(using closure). However I just discovered that constructors can have private variables by defining variables without the "this" keyword. So my question is as follows: Why would someone choose factory functions over constructors? I can't see a valid reason for wanting to avoid prototypal inheritance since it can provide extra behaviour when needed and constructors can implement private variables as well.

Top answer
1 of 8
190

The basic difference is that a constructor function is used with the new keyword (which causes JavaScript to automatically create a new object, set this within the function to that object, and return the object):

var objFromConstructor = new ConstructorFunction();

A factory function is called like a "regular" function:

var objFromFactory = factoryFunction();

But for it to be considered a "factory" it would need to return a new instance of some object: you wouldn't call it a "factory" function if it just returned a boolean or something. This does not happen automatically like with new, but it does allow more flexibility for some cases.

In a really simple example the functions referenced above might look something like this:

function ConstructorFunction() {
   this.someProp1 = "1";
   this.someProp2 = "2";
}
ConstructorFunction.prototype.someMethod = function() { /* whatever */ };

function factoryFunction() {
   var obj = {
      someProp1 : "1",
      someProp2 : "2",
      someMethod: function() { /* whatever */ }
   };
   // other code to manipulate obj in some way here
   return obj;
}

Of course you can make factory functions much more complicated than that simple example.

One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.

2 of 8
141

Benefits of using constructors

  • Most books teach you to use constructors and new

  • this refers to the new object

  • Some people like the way var myFoo = new Foo(); reads.

Drawbacks

  • Details of instantiation get leaked into the calling API (via the new requirement), so all callers are tightly coupled to the constructor implementation. If you ever need the additional flexibility of the factory, you'll have to refactor all callers (admittedly the exceptional case, rather than the rule).

  • Forgetting new is such a common bug, you should strongly consider adding a boilerplate check to ensure that the constructor is called correctly ( if (!(this instanceof Foo)) { return new Foo() } ). EDIT: Since ES6 (ES2015) you can't forget new with a class constructor, or the constructor will throw an error.

  • If you do the instanceof check, it leaves ambiguity as to whether or not new is required. In my opinion, it shouldn't be. You've effectively short circuited the new requirement, which means you could erase drawback #1. But then you've just got a factory function in all but name, with additional boilerplate, a capital letter, and less flexible this context.

Constructors break the Open / Closed Principle

But my main concern is that it violates the open/closed principle. You start out exporting a constructor, users start using the constructor, then down the road you realize you need the flexibility of a factory, instead (for instance, to switch the implementation to use object pools, or to instantiate across execution contexts, or to have more inheritance flexibility using prototypal OO).

You're stuck, though. You can't make the change without breaking all the code that calls your constructor with new. You can't switch to using object pools for performance gains, for instance.

Also, using constructors gives you a deceptive instanceof that doesn't work across execution contexts, and doesn't work if your constructor prototype gets swapped out. It will also fail if you start out returning this from your constructor, and then switch to exporting an arbitrary object, which you'd have to do to enable factory-like behavior in your constructor.

Benefits of using factories

  • Less code - no boilerplate required.

  • You can return any arbitrary object, and use any arbitrary prototype - giving you more flexibility to create various types of objects which implement the same API. For example, a media player that can create instances of both HTML5 and flash players, or an event library which can emit DOM events or web socket events. Factories can also instantiate objects across execution contexts, take advantage of object pools, and allow for more flexible prototypal inheritance models.

  • You'd never have a need to convert from a factory to a constructor, so refactoring will never be an issue.

  • No ambiguity about using new. Don't. (It will make this behave badly, see next point).

  • this behaves as it normally would - so you can use it to access the parent object (for example, inside player.create(), this refers to player, just like any other method invocation would. call and apply also reassign this, as expected. If you store prototypes on the parent object, that can be a great way to dynamically swap out functionality, and enable very flexible polymorphism for your object instantiation.

  • No ambiguity about whether or not to capitalize. Don't. Lint tools will complain, and then you'll be tempted to try to use new, and then you'll undo the benefit described above.

  • Some people like the way var myFoo = foo(); or var myFoo = foo.create(); reads.

Drawbacks

  • new doesn't behave as expected (see above). Solution: don't use it.

  • this doesn't refer to the new object (instead, if the constructor is invoked with dot notation or square bracket notation, e.g. foo.bar() - this refers to foo - just like every other JavaScript method -- see benefits).

🌐
DEV Community
dev.to › bchau › factory-functions-vs-constructors-500m
Factory Functions vs Constructors - DEV Community
April 27, 2022 - A constructor function is another javascript pattern, that is very similar to factory functions. Though, unlike factory functions, constructor functions do not actually return an object.
🌐
Medium
medium.com › @raileohang › factory-functions-constructor-functions-in-javascript-6ac62d883b01
Factory Functions & Constructor Functions in JavaScript | by Leohang Rai | Medium | Medium
May 11, 2025 - Factory functions are basically functions that create and return objects. Unlike Constructor functions, which are used with the new operator to create instances, Factory functions are called like regular functions and simply return a new object.
🌐
The Odin Project
theodinproject.com › lessons › node-path-javascript-factory-functions-and-the-module-pattern
Factory Functions and the Module Pattern | The Odin Project
This is all very similar to the constructor, except this is just a normal function, meaning we do not need to call it with the new keyword. Some may get confused by the way the returned object is written in the factory function example. In 2015, a shortcut to creating objects was added to JavaScript.
🌐
Reddit
reddit.com › r/learnprogramming › factory functions and constructors (what's the difference??)
r/learnprogramming on Reddit: Factory Functions and Constructors (What's the difference??)
October 17, 2021 -

Can anyone explain me what's the difference between factory functions and constructors?

I'm at THIS LESSON from The Odin Project and after reading it a bunch of times, I still can't understand the difference. I watched a couple of videos on the matter but I can wrap my head around it.

I understand that with a constructor you new to use the keyword new to create an instance of the object:

function Player(name, marker) { 
    this.name = name
    this.marker = marker 
}

const player = new Player('steve', 'X')

And with the factory function you return a new object:

const playerFactory = (name, marker) => { 
    return { name, marker }
}

const player = playerFactory('steve', 'X')

Soooo, that's the only difference that I found. Am I stupid or what? Please help.

note: english it's not my first language. In case I made a spelling mistake.

Top answer
1 of 4
5
Commenting because I want to know the answer and for this question to gain visibility
2 of 4
5
There is almost no utility in that example. The main reason to have factories is to do something other than just construct. Also because (in other languages) you really don't want to throw exceptions from constructors. The factory can be used (primitive use) as a wrapper around a constructor (or constructors) that sanity checks values and returns an object or signals an error (either by returning, say, null or triggering an exception or whatever). That is the most primitive use case of factories. The more useful case is when the factory wraps around some other constructs. For instance, maybe you have an ORM (object relational mapping). You could use a factory that is aware of the database and returns properly populated objects based on data in the database. You wouldn't (usually) want to make your constructor aware of a database, it's mixing different parts of the system. So you'd have a Player class with a constructor and a PlayerFromDatabase factory which is aware of the database. Another potential use-case is when the factory and objects being constructed represent heavyweight (memory heavy, usually) or otherwise constrained resources (you can only permit X concurrent instances, for whatever reason). In the former case, the factory is aware of all the already created objects and returns (rather than duplicates) an existing one if it satisfies the needs. An example of that would be with loading texture files in a video game. The factory is aware of all already opened texture files, when you request a new one it checks to see if it's already been loaded and either loads the file and makes a new object or returns the existing one. Potentially saving you GBs of memory usage if a texture is used all over the place. In the second case, resource constrained, you get a similar effect. Instead of calling a constructor and having it error out (usually a bad thing, also mixes parts of the system again) you let the factory be aware of the constraint (there can be only 5 open DB connections at a time, because you work for my company and have a shitty DBA). So you ask the factory for a new DB connection and it gives you an error or null result. Or in a multithreaded environment it will block (if that's desirable for your system) and wait until one of the existing DB connections is closed, and give you a new one (or recycle it if it's "freed", not closed but no longer in use by the other user). Summary: A dumb wrapper around a normal constructor, not very useful A smart wrapper around a normal constructor preventing bad instantiations or assigning default values A wrapper around another set of data so you don't mix concerns (the db and the Player class) A wrapper around heavyweight objects to provide caching or similar mechanisms A wrapper around a constrained resource to prevent too many instantiations (for whatever reason it may be constrained) and proper sharing/recycling/removing There are other reasons and ways to use them, but in my experience this is pretty much the full run I've seen. The first is not helpful, the second is middlingly useful, and the other three are much more valid use-cases of the Factory pattern.
🌐
YouTube
youtube.com › watch
Factory Function vs. Constructor vs. Class - JavaScript Tutorial - YouTube
The JavaScript Tool I'm using to demonstrate:https://runjs.app/ColorCodeColorCode Etsy Merchandise store:https://www.etsy.com/shop/ColorCodeStoreWhat is the ...
Published   May 21, 2021
Find elsewhere
🌐
YouTube
youtube.com › watch
JavaScript Factory vs. Constructor in 1 Minute #shorts - YouTube
Full video: https://youtu.be/fbuyliXlDGIWhat is the difference between a Factory Function and a Constructor in JavaScript?Factory vs. Constructor from the se...
Published   October 21, 2022
🌐
Reddit
reddit.com › r/learnjavascript › kind of confused with constructors and factory functions..
r/learnjavascript on Reddit: Kind of confused with constructors and factory functions..
March 14, 2022 -

Here's what I got until now..

Both ways are done to create a "blueprint" for numerous objects that share some functionality..

The factory function returns a new object, also easier to encapsulate things by simply not returning them but by using closure they can still be accessed from inside the function..

With constructors you need to use the "new" keyword in the object instantiation, behind the scenes the function creates an object called "this" and returns it with the code you wrote.

In the course I'm doing (The Odin Project), they advise using factory functions over constructors.. Also instead of using inheritance, to use composition.. Which for me is great, because out of all of these, factory functions + composition is what I understood the most..

Constructors, "this" keyword, prototypes and all that still kind of confuse me..

I wrote this little code to try and see if I could do something with factory functions and compositions.. Did I do it right or could have it have been better?

https://jsfiddle.net/va35kyrd/

https://codesandbox.io/s/muddy-fast-nc2nfl?file=/src/index.js

The idea is that player1(p1) has power of flight, p2 has power of invisibility.. Both can attack and heal, and then p3 is overpowered so he has both powers and more health and healing ability..

I feel like I messed up with p3, passing in the if statement in line 17 could get messy with lots of different players.. If I set p3 health and healing when I create it, it still uses the default ones of 5 and 3 (line 14).

Top answer
1 of 3
9
The OOP chapters in the Odin Project are terrible, I do not recommend them. They are parroting common misconceptions about classes and object composition. I’ll try to write a more detailed answer and review of your code tomorrow (and show an alternative way to do it with actual composition). Edit: Didn't find enough time to write a detailed explanation, but here's my take on the Player class: https://github.com/caderek/oop-in-modern-js/tree/main/examples/game If you are still interested, let me know - so I will explain why I wrote it this way. Here's my initial write-up that tries to clear some misconceptions about classes: https://github.com/caderek/oop-in-modern-js/blob/main/README.md
2 of 3
3
When going down the road of data and methods, in an OOP style, which you seem to be after here, you want to be clear on the point of the pattern. There is state, the data contained within the object, and then there a methods, the functions that manipulate that state somehow. Given what you have, I couldn't help fiddling with it a little. I ended up with this: // these are the mutable parts of your Player // the "state" const playerState = (name, health, healingPotion) => ({ name, health, healingPotion }); // your powers should take the object and work with that const flight = (obj) => ({ fly: () => console.log(`${obj.name()} is flying`) }); const invisibility = (obj) => ({ invisible: () => console.log(`where is ${obj.name()}?`) }); const Player = (initialState, ...powers) => { let state = { ...initialState }; // make a copy, this is our mutable state // let's build our object, knowing what we know const methods = { name: () => state.name, dealDamage: () => state.health -= 1, health: () => state.health, heal: () => { if (state.healingPotion === 0) { console.log("No more potions left"); } else { state.healingPotion--; state.health++; console.log(` ${state.name} restored health. ${state.healingPotion} healing potions left; Health: ${state.health}; `); } }, attack: opponent => { console.log(`${state.name} has attacked ${opponent.name()}`); opponent.dealDamage(); if (opponent.health() <= 0) { console.log(`${opponent.name()} has died`); } }, // added this one, I'm lazy show: () => console.log(`${state.name}: [${state.health} H, ${state.healingPotion} potions]`) }; // now, add some powers // ok, this is a little tricky, but all we're doing is taking our starting methods // and tacking on each power return powers.reduce((obj, newPower) => ({...obj, ...(newPower(obj)) }), methods); }; const p1 = Player(playerState("p1",5,3), flight); const p2 = Player(playerState("p2",5,3), invisibility); //creating a player that has both flight, invisibility + more health and healing const p3 = Player(playerState("p3",999,999), flight, invisibility); //-------------------------------------------------------------------// p1.show(); p2.show(); p1.fly(); //p1 can fly // p1.invisible() //p2 can't turn invisible p2.invisible(); //p2 can turn invisible p1.attack(p2); p1.show(); p2.show(); p3.show(); Modern javascript handles class style OOP much better than it used it. You might consider going that route. const createPower = (name, action) => ({name, action}); class Player { constructor(name, health, healingPotion, ...powers) { [this.name, this.health, this.healingPotion, this.powers] = [name, health, healingPotion, powers]; } getName = () => this.name; getPowers = () => this.powers.map(x => x.name); usePower = name => this.powers.find(x => x.name === name).action(this); dealDamage = (n = 1) => this.health -= n; isAlive = () => this.health > 0; getHealth = () => this.health; show = () => console.log(`${this.name}: [${this.health} H, ${this.healingPotion} potions] [${this.getPowers()}]`); heal = () => { if (this.healingPotion === 0) { console.log("No more potions left"); } else { this.healingPotion--; this.health++; this.show(); } } attack = (opponent) => { console.log(`${this.name} has attacked ${opponent.getName()}`); opponent.dealDamage(); if (!opponent.isAlive()) { console.log(`${opponent.getName()} has died`); } } }; const flight = createPower("fly", x => console.log(`${x.getName()} is flying`)); const invisibility = createPower("invisible", x => console.log(`where is ${x.getName()}?`)); const p1 = new Player("p1", 5, 3, flight); const p2 = new Player("p2", 5, 3, invisibility); const p3 = new Player("p3", 999, 999, flight, invisibility); p1.show(); p2.show(); p1.usePower("fly"); // p2.usePower("fly"); p1.attack(p2); p1.show(); p2.show(); p3.show(); There are some subtle advantages to the class route. e.g. with the manual create object, all those methods are new objects. With a class, they are all shared.
🌐
OneCompiler
onecompiler.com › posts › 3ukppj6wx › factory-functions-vs-constructor-functions
Factory functions Vs Constructor Functions - Posts - OneCompiler
April 27, 2019 - In the constructor function, the new keyword is used to call a function. By using the new keyword function will return an empty object product in the above case and point out this keyword to the product object. Whereas in factory functions, the object will be created with the function call.
🌐
Reddit
reddit.com › r/javascript › factory functions vs constructor functions: the impact on the prototype chain?
r/javascript on Reddit: Factory functions vs Constructor functions: The impact on the prototype chain?
February 12, 2016 -

tl;dr: help me understand which inheritance pattern is 'best' (in which situation)

I've read Douglas Crockford's "The Good Parts" and I'm working my way through Haverbeke's "Elequent Javascript." These books take a different approach towards inheritance with Crockford recommending the use of 'factory functions' to perform inheritance and discouraging 'psuedoclassical' or constructor based inheritance. (A quick example for clarity)

// factory function (assume a mammal() factory function exists elsewhere)
var cat = function(name,){
  var that = object.Create(mammal(name));
  that.says = function() { console.log('my name is ' + this.name ) };
  return that;
};
var garfield = cat('garfield');

vs

// psuedoclassical (assume a Mammal() constructor exists elsewhere)
var Cat = function(name){
  this.name = name;
};
Cat.prototype = new Mammal( );
Cat.prototype.says = function() { console.log('my name is ' + this.name ) };
var heathcliff = new Cat('heathcliff');

Can you guys weigh in on the pros/cons and any personal preference you may have for either of these mechanisms? Crockford comes out pretty strongly on the former method but he seems to be the only one that pushes it. Not to mention that ES6 appears to introduce keywords to further commit to the psuedoclassical model, though much of the comments surrounding that functionality state that this is all just masking the 'true nature' of javascript (ie: prototypes, not classes).

The best that I can figure the actual functional difference between these two mechanisms are:

  • In the factory function pattern you don't end up with a prototype that can (easily) be used to modify all instances of the child class. Because an object, not a constructor function, is the prototype you must maintain that object if you want to affect all children. In the example above this is not possible because I wrote it to call 'mammal(name)' which would give us a different instance every time.

  • In the factory function pattern some of the new functionality which allows you to control the types of the properties that you add (for example to prevent them from being enumerated or to create get/set functions) is unavailable.

Sorry for the wall of text... I could take this to stackoverflow but I figured I'd start here.

🌐
DEV Community
dev.to › matheusjulidori › do-you-know-how-it-works-factory-functions-vs-constructor-functions-47kh
Do you know how it works? - Factory Functions vs Constructor Functions - DEV Community
June 2, 2025 - Factory functions return objects explicitly and offer better flexibility and encapsulation (closures), while constructor functions use the new keyword and automatically set up prototypal inheritance, sharing methods across instances. In this post, we break down real-world examples, when to use each one, and why understanding both patterns makes your JavaScript code more powerful, scalable, and readable.
🌐
Colorcode
colorcode.io › courses › 10-things-js › js-factory-vs-constructor
Factory Function vs. Constructor
JavaScript DOM API, one of the most underrated but fundamentally important Web APIs. ... Two major rules that make any function pure, benefits of pure function, as well as why some functions can't be pure. ... Functions in JavaScript are First-Class. But what does that mean?
🌐
Codecademy Forums
discuss.codecademy.com › get help › javascript
Is there still a purpose to factory functions or should we always use classes? - JavaScript - Codecademy Forums
April 21, 2019 - Hello! I am wondering if classes make the ‘factory functions’ we learned during the objects lesson obsolete? Is there a time where it is more appropriate to use a factory function? Or should we generally always use classes to build multiple objects?
🌐
Medium
medium.com › @erinlejhimmy › factory-functions-vs-constructor-functions-in-javascript-8bef9510be3c
Factory Functions Vs Constructor Functions in JavaScript. | by The ERIN | Medium
August 20, 2020 - In Factory Function all our Logic ... if we found any bug in our function some time in the future. Constructor Functions are used to construct or create an object....
🌐
Medium
blog.bigoodyssey.com › javascript-factory-functions-vs-constructor-functions-585919818afe
JavaScript Factory functions vs Constructor functions. | by Chamika Kasun | Medium
June 7, 2020 - A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object.
🌐
DEV Community
dev.to › snevy1 › classes-vs-factory-functions-in-javascript-4fjn
Classes vs Factory functions in Javascript - DEV Community
November 30, 2023 - Inside of the function we add a constructor that holds the parameters to be used. Notice that instead of adding increment and login methods on the prototype explicitly, we nicely tuck them inside the class object though under the hood they are added to the prototype(implicitly) So if constructors and classes do essentially the same thing why should we use classes instead of constructors? Classes are easy to read. By using classes, Javascript tries to follow the normal convention of object-oriented programming, though it is still a prototypical-based language.