What is a constructor function?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #JS Basics

Brief Answer

constructor function is a regular function used to create objects of the same type. Essentially, it’s a “template” or “blueprint” for creating similar objects. Constructor functions are called with the [new] keyword.

// Constructor function
function User(name, age) {
  this.name = name;
  this.age = age;
}
 
// Creating objects
const user1 = new User('John', 25);
const user2 = new User('Peter', 30);
 
console.log(user1.name); // 'John'
console.log(user2.name); // 'Peter'

Full Answer

A constructor function is just a regular function that works as a “factory” for producing similar objects. Think of it as a machine at a factory that makes identical parts. 🏭

What is a Constructor Function

It’s a regular function, but with a special purpose — to create objects. The distinguishing feature: it’s called with the [new] keyword.

Simple Examples

Basic Constructor

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
  this.start = function() {
    console.log(this.brand + ' ' + this.model + ' started');
  };
}
 
// Create cars from the "blueprint"
const car1 = new Car('Toyota', 'Camry');
const car2 = new Car('Honda', 'Civic');
 
car1.start(); // 'Toyota Camry started'
car2.start(); // 'Honda Civic started'

Constructor Without Parameters

function Counter() {
  this.value = 0;
  this.increment = function() {
    this.value++;
  };
}
 
const counter = new Counter();
counter.increment();
console.log(counter.value); // 1

How Constructors Work

The new Keyword

function Person(name) {
  // this automatically becomes an empty object {}
  this.name = name;
  // return this; (happens automatically)
}
 
const person = new Person('John');
// 1. An empty object {} is created
// 2. This object becomes this
// 3. Function code is executed
// 4. this is automatically returned

What Happens “Under the Hood”

// When you write:
new User('John');
 
// JavaScript does:
// 1. const obj = {}; (creates empty object)
// 2. obj.__proto__ = User.prototype; (sets up prototype)
// 3. User.call(obj, 'John'); (calls function with obj as this)
// 4. return obj; (returns object)

When to Use Constructors

For Creating Similar Objects

function Book(title, author) {
  this.title = title;
  this.author = author;
  this.getInfo = function() {
    return this.title + ' by ' + this.author;
  };
}
 
// Create a library
const books = [
  new Book('War and Peace', 'Tolstoy'),
  new Book('Crime and Punishment', 'Dostoevsky'),
  new Book('The Master and Margarita', 'Bulgakov')
];

For Code Organization

function Calculator() {
  this.add = function(a, b) {
    return a + b;
  };
  
  this.multiply = function(a, b) {
    return a * b;
  };
}
 
const calc = new Calculator();
console.log(calc.add(5, 3)); // 8

Common Mistakes

Forgetting the new Keyword

function User(name) {
  this.name = name;
}
 
// ❌ Without new — this will be window/undefined
const user = User('John');
console.log(user); // undefined
console.log(window.name); // 'John' (in non-strict mode)
 
// ✅ With new — everything works correctly
const user2 = new User('John');
console.log(user2.name); // 'John'

Arrow Functions as Constructors

// ❌ Arrow functions can't be constructors
const User = (name) => {
  this.name = name;
};
 
// new User('John'); // Error!
 
// ✅ Regular functions work
function User(name) {
  this.name = name;
}
 
new User('John'); // Works!

Simple Rules

  1. Constructor — function for creating similar objects 🏗️
  2. Call with new — must use the new keyword 🆕
  3. this — inside constructor automatically becomes new object 🎯
  4. Return — constructor automatically returns this 📤
  5. Capital name — by convention starts with capital letter 📝

Constructor functions are a convenient way to create many similar objects. This is the foundation of object-oriented programming in JavaScript! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪