Classes vs Factory functions in Javascript
Tags: javascript, beginners, programming, discuss
Published: 2023-11-30 16:12:10



#### Between Factory Functions and Classes which is better?

In Javascript, you can arrange your code  using object oriented patterns such as factory functions, classes and constructors.Choosing the right pattern can be tricky. In this article, I will explain what classes, constructors and factory functions are and how to use them in various situations.

In my previous article, I discussed extensively how creating objects by classes and constructors is better than object literal.Check it out [here](https://dev.to/snevy1/object-oriented-programming-in-javascript-a-comprehensive-guide-402h).

## Classes in Javascript

If you know constructors then classes shouldn't be hard to grasp. Classes are a syntactic sugar of constructors in Javascript.

The code below shows a constructor function.

```javascript
function playerCreator(name, score) {
  this.name = name;
  this.score = score;
}

playerCreator.prototype.increment = function () {
  this.score++;
};
playerCreator.prototype.login = function () {
  this.login = false;
};
```



Notice how the **increment** and **login** functions are placed on the prototype.They are shared functions so any object created by the constructor has access to the methods. This saves memory.

This next code shows a class object.
```javascript

class playerCreator{

  constructor(name,score){
   this.name = name;
  this.score = score;
  }

increment: function () {
  this.score++;
};

login:  function () {
  this.login = false;
};



}
```

When we create a class object we start with the keyword **class** then a function name. 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.

Also, classes are not native to JavaScript but are widely used in other object-oriented programming languages such as C# and Java. To avoid confusion that developers from these languages face when they encounter Javascript, classes are a better solution.

## Factory Functions


![Factory functions in javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwypdvy02rfm4porg6mb.png)

What are factory functions? Factory functions are functions that return a new object. They are quite similar to classes, but they utilize the power of closures in that, they don't use the **new** keyword.

Once you call the function, it sets up and returns a new object.

Below is how we would implement a factory function:

```javascript
function playerCreator(name, score) {
  return {
    name: name,
    score: score,
    increment() {
      return (this.score += 1);
    },
    login() {
      return (this.login = false);
    },
  };
}

let player1 = playerCreator("John", 8);

player1.increment(); // 9
```

Benefits of using Factory Functions over Classes in javascript

- There is no use of **this** keyword when instantiating variables. It is only used inside methods. This reduces the confusion of the **this** keyword.
- There is no use of the **new** keyword which is often forgotten when creating objects using classes.
- It is easier to setup since it looks quite similar to regular functions.
- Simplicity - Factory functions provide a more straightforward and flexible way to create objects. They don't have the syntactic complexities that come with class declarations and prototypes, making them more approachable for developers who prefer a simpler syntax.

- Encapsulation with Closures: It is easy to encapsulate private variables and objects with Factory functions since is natural to them.This enhances data privacy and abstraction.

Benefits of using Classes over Factory functions in Javascript

- Classes save memory so they are suitable when creating large applications that require creation of thousands of objects.
- Classes are used in many programming languages hence it is a cleaner way to follow object oriented programming paradigm.
- Inheritance: Classes support the concept of inheritance, making it easier to create a hierarchy of objects. You can use the extends keyword to create a subclass that inherits from a superclass.
```Javascript
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  // Additional methods or overrides
}

const student1 = new Student('James', 18, 'A');

```

- 'instanceof' Operator: Classes make use of the instanceof operator, which can be useful for type-checking and determining if an object is an instance of a particular class.

```Javascript
console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person);  // true

```

## Conclusion

The choice between classes and factory functions depend on your specific needs and which pattern you are comfortable with.

In my opinion, factory functions are great and the performance benefit of classes is minimal. Let me know your opinion in the comments below.

Follow me on:

[Twitter](https://twitter.com/Sneviy)

[Linkedin](https://www.linkedin.com/in/nevily-simiyu/)