The Factory Function is similar to constructor functions/class functions, but instead of using new to create an object, factory functions simply creates an object and returns it.
they do not require the use of the ‘this‘ keyword for inner values or the use of the ‘new‘ keyword when instantiating new objects.
Factory Functions can contain inner values, methods, etc. just like normal regular functions. Factory Functions differ from regular functions as they always return an object, which will contain any value, method, etc.
If we have complex logic, and we have to create multiple objects again and again that have the same logic, we can write the logic once in a function and use that function as a factory to create our objects. It’s exactly the same as a real-world factory producing products.
Factory functions follow the Factory Method Pattern (a Creational Pattern).
Instead of the client (the code using the object) calling new and knowing the specific class details, it calls a 'Factory' and asks for an object. The Factory handles the complexity of creation.
Decoupling: The rest of your app doesn't need to know how the object is built; it just needs the resulting object.
Object Composition: Instead of deep inheritance chains (Dog -> Mammal -> Animal), a factory can 'compose' an object by mixing together different small behaviors.
Favor Composition over Inheritance.