JavaScriptMedium
What is the Factory pattern and how is it used?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
The Factory pattern is a design pattern used to create objects without specifying the exact class of the object that will be created. It provides a way to encapsulate the instantiation logic and can be particularly useful when the creation process is complex or when the type of object to be created is determined at runtime.
For example, in JavaScript, you can use a factory function to create different types of objects:
js
function createAnimal(type) {
if (type === "dog") {
return { sound: "woof" };
} else if (type === "cat") {
return { sound: "meow" };
}
}
const dog = createAnimal("dog");
const cat = createAnimal("cat");
