A Simple Explanation of the Factory Method in JavaScript

Katana Haley
2 min readJan 27, 2023

The factory method in JavaScript is a design pattern that creates objects without specifying the exact class of object that will be created. Instead, a factory class defines a method that creates and returns an object, but the actual class of the object is determined at runtime.

This allows for greater flexibility and ease of modification in the future, as the specific class of object can be changed without affecting the rest of the code. The factory method is often used in situations where a class has multiple potential subclasses, or where the decision of which class to use is dependent on runtime conditions.

Factory method code example

Here is an example of a simple factory method in JavaScript that creates objects of various types based on a given “type” parameter:

In this example, the ShapeFactory class contains a single method, createShape(), which takes a single parameter, type. Based on the value of type, the method returns a new object of the corresponding class. In this case, it creates new instance of Circle, Square and Triangle classes.

In this example, the factory method is used to create objects of various types (Circle, Square, and Triangle) without specifying the exact class of object that will be created. This allows for greater flexibility and ease of modification in the future, as the specific class of object can be changed without affecting the rest of the code.

If you enjoyed this article, give it a clap! Read more web development articles here.

--

--

Katana Haley

Hard Rock/ Heavy Metal Singer of Hathor Rising | Software Engineer | Author