Join the Nature Wishlist Discord to get help, share your projects, and discuss JavaScript.
🧩 ⏐ Design Patterns
6. Factory Pattern

Factory Pattern

Use a factory function in order to create objects


With the Factory Pattern, we can use a special function - the factory function - to create many of the same objects.


A factory function can be any function that returns an object.

const createUser = (firstName, lastName) => ({
  id: crypto.randomUUID(),
  fullName: `${firstName} ${lastName}`,
createUser("John", "Doe");
createUser("Sarah", "Doe");
createUser("Lydia", "Hallie");


DRY: The factory pattern is useful when we have to create multiple objects that share the same properties, without having to repeat the same code over and over. A factory function can easily return a custom object depending on the current environment, or user-specific configuration.

Not really a pattern: In JavaScript, the factory pattern isn't much more than a function that returns an object without using the new keyword. ES6 arrow functions allow us to create small factory functions that implicitly return an object each time.

However, in many cases it may be more memory efficient to create new instances instead of new objects each time.

class User {
  constructor(firstName, lastName, email) {
    this.firstName = firstName;
    this.lastName = lastName; = email;
  async getPosts() {
    const posts = await fetch(`${}`);
    return posts;
const user1 = new User({
  firstName: "John",
  lastName: "Doe",
  email: "",
const user2 = new User({
  firstName: "Jane",
  lastName: "Doe",
  email: "",

The fullName method is the same for all the objects that were created. By creating new instances, the fullName method is available on the prototype instead of on the objec, which saves memory.



Refactor the following code to use a createBook factory function.