Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a constructor function in JavaScript

What is a Constructor Function?

In the world of JavaScript, a constructor function plays a crucial role. It might sound like a high-tech term, but it's not. In simple words, a constructor function is a special kind of function that helps to create and initialize an object created from a particular class.

In everyday life, consider it as a blueprint for a house. You provide the blueprint or the plan (constructor function), and it helps in building the house (object).

A Peek into Functions

Before we delve into constructor functions, let's take a quick peek into what functions are.

A function in JavaScript is a block of code that does a specific task. Think of it as a machine in a factory. You feed it some raw materials (input), it processes them, and then spits out a finished product (output). Here's a simple example:

function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Alice")); // This will output: Hello, Alice

Diving into Constructor Functions

A constructor function in JavaScript is not very different from a regular function. The difference lies in how we use it. We use a constructor function with the new keyword to create new objects. Here's a basic example:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

let myCar = new Car('Toyota', 'Corolla', 2005);
console.log(myCar); // This will output: Car { make: 'Toyota', model: 'Corolla', year: 2005 }

In this example, Car is a constructor function. We use it with the new keyword to create a new car object. The this