js
Constructor Function Factory Function

Constructor Function vs. Factory Function

Constructor Function

A constructor function in JavaScript is used to create instances of objects. It uses the new keyword to create an object, and this refers to the new object being created.

Example

function Car(make, model) {
  this.make = make;
  this.model = model;
}
 
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar); // Output: Car { make: 'Toyota', model: 'Corolla' }

Factory Function

A factory function is a regular function that returns an object. It does not use the new keyword, and this is not used.

Example

function createCar(make, model) {
  return {
    make: make,
    model: model
  };
}
 
const myCar = createCar('Toyota', 'Corolla');
console.log(myCar); // Output: { make: 'Toyota', model: 'Corolla' }