JavaScript Constructors

A constructor in JavaScript is a special method used to initialize objects created from a class. It allows you to assign initial values to an object’s properties when the object is created.

The constructor() method is commonly used to initialize properties such as a user’s name, age, email, or an employee’s role and salary.

JavaScript classes were introduced in ES6 (ECMAScript 2015). The constructor makes it easier to create multiple objects with the same structure while allowing each object to store different values.

In this tutorial, you will learn how JavaScript constructors work, how to use constructor parameters, how default values work in constructors, and the difference between class constructors and constructor functions.

What Is a Constructor in JavaScript?

A constructor is a special method inside a JavaScript class that runs automatically when you create an instance using the new keyword.

It is usually used to initialize the properties of the new object.

Example of a Constructor

class Student {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

const student1 = new Student("Rahul", 20);

console.log(student1.name);
console.log(student1.age);

Output:

Rahul
20

In this example:

  • class Student defines a class named Student.
  • constructor(name, age) defines the constructor method.
  • this.name = name assigns the provided name to the new object.
  • this.age = age assigns the provided age to the new object.
  • new Student("Rahul", 20) creates a new instance and passes values to the constructor.

The constructor runs when the instance is created, so the object’s properties are initialized automatically.

To understand the broader concept, read about JavaScript Classes and how classes are used to create objects.

Constructor Syntax in JavaScript

The basic syntax of a constructor inside a class is:

class ClassName {
    constructor(parameters) {
        // Initialize object properties
    }
}

The constructor keyword identifies the special method. Parameters receive the values passed when an object is created.

For example:

class Employee {
    constructor(name, role) {
        this.name = name;
        this.role = role;
    }
}

When you create an employee object, JavaScript calls the constructor and initializes its properties.

How the Constructor Works

When you use new with a class, JavaScript creates a new object, establishes its prototype, and calls the class constructor with the supplied arguments. The constructor initializes the object.

Consider this example:

class Car {
    constructor(brand, color) {
        this.brand = brand;
        this.color = color;
    }
}

const car1 = new Car("Toyota", "White");
const car2 = new Car("Honda", "Black");

console.log(car1.brand);
console.log(car2.brand);

Output:

Toyota
Honda

Both objects are created from the same class, but they have different property values.

The car1 object stores "Toyota" as its brand, while car2 stores "Honda".

This makes constructors useful when an application needs to create many objects with a consistent structure.

Using Parameters in a Constructor

Constructor parameters allow you to provide different values for each object.

Example

class Product {
    constructor(name, price, category) {
        this.name = name;
        this.price = price;
        this.category = category;
    }

    displayDetails() {
        console.log(`Product: ${this.name}`);
        console.log(`Price: ₹${this.price}`);
        console.log(`Category: ${this.category}`);
    }
}

const product1 = new Product("Laptop", 55000, "Electronics");
const product2 = new Product("Headphones", 2000, "Accessories");

product1.displayDetails();
product2.displayDetails();

Output:

Product: Laptop
Price: ₹55000
Category: Electronics
Product: Headphones
Price: ₹2000
Category: Accessories

The constructor initializes the three properties for each product. The displayDetails() method then uses those properties to display the product information.

This pattern is useful for representing users, products, employees, students, and other entities in an application.

Using Default Parameters in Constructors

You can use default parameters to provide fallback values when an argument is missing or explicitly passed as undefined.

class User {
    constructor(name = "Guest", city = "Hyderabad") {
        this.name = name;
        this.city = city;
    }

    display() {
        console.log(`${this.name} lives in ${this.city}.`);
    }
}

const user1 = new User("Rahul", "Vijayawada");
const user2 = new User();

user1.display();
user2.display();

Output:

Rahul lives in Vijayawada.
Guest lives in Hyderabad.

When no arguments are provided, the constructor uses the default values.

Default parameters do not replace values such as null, 0, or an empty string. They apply when an argument is missing or undefined.

Using Methods Alongside Constructors

A constructor initializes an object, while other class methods define what the object can do.

class BankAccount {
    constructor(owner, balance) {
        this.owner = owner;
        this.balance = balance;
    }

    deposit(amount) {
        this.balance += amount;
        return this.balance;
    }

    getBalance() {
        return this.balance;
    }
}

const account = new BankAccount("Priya", 1000);

account.deposit(500);

console.log(account.owner);
console.log(account.getBalance());

Output:

Priya
1500

The constructor initializes the account owner and starting balance. The deposit() method updates the balance, while getBalance() returns the current balance.

This example demonstrates how constructors and methods work together to manage an object’s data and behavior.

What Happens When a Class Has No Constructor?

You do not have to write a constructor in every class.

If you omit the constructor, JavaScript provides a default constructor. For a basic class without inheritance, this behaves like an empty constructor that accepts the arguments but does not automatically assign them to properties.

class Message {
    show() {
        console.log("Welcome to JavaScript!");
    }
}

const message = new Message();

message.show();

Output:

Welcome to JavaScript!

The object can call the show() method even though the class does not define a constructor.

However, if you want to initialize properties from supplied arguments, you generally need to define a constructor or use another object-creation approach.

Constructor vs Regular Method

A constructor and a regular method serve different purposes within a class.

FeatureConstructorRegular Method
PurposeInitializes a new instancePerforms an operation
NameMust be constructorCan have a chosen name
When it runsAutomatically during instance creation with newWhen explicitly called
How often it runsOnce per normal instance constructionWhenever called
Exampleconstructor(name) { ... }greet() { ... }

For example:

class Person {
    constructor(name) {
        this.name = name;
    }

    greet() {
        return `Hello, ${this.name}!`;
    }
}

const person = new Person("Ayesha");

console.log(person.greet());

Output:

Hello, Ayesha!

The constructor initializes the name property. The greet() method returns a greeting when called.

Constructor Functions Before ES6

Before ES6 classes, JavaScript developers often used constructor functions to create objects with shared properties and methods.

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.greet = function() {
    return `Hello, ${this.name}!`;
};

const person = new Person("Rahul", 25);

console.log(person.name);
console.log(person.greet());

Output:

Rahul
Hello, Rahul!

Here, Person is a constructor function. Calling it with new creates an object and binds this to that new object during the function call.

A class-based version looks like this:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        return `Hello, ${this.name}!`;
    }
}

const person = new Person("Rahul", 25);

console.log(person.name);
console.log(person.greet());

Output:

Rahul
Hello, Rahul!

Both approaches can create objects with similar behavior. Class syntax provides a more structured way to write constructors and methods, but JavaScript classes still use prototypes.

Common Mistakes with JavaScript Constructors

Forgetting the new Keyword

Class constructors must be invoked using new.

Incorrect:

class Student {
    constructor(name) {
        this.name = name;
    }
}

// Student("Rahul"); // TypeError

Correct:

const student = new Student("Rahul");

console.log(student.name);

Output:

Rahul

Using the Wrong Constructor Name

The special class method must be named constructor, not construct or initialize.

class Student {
    constructor(name) {
        this.name = name;
    }
}

A method with another name is treated as a regular method rather than the constructor.

Forgetting to Assign Properties

Declaring a constructor parameter does not automatically create a property with the same name.

class Student {
    constructor(name) {
        name = name;
    }
}

const student = new Student("Rahul");

console.log(student.name);

Output:

undefined

The parameter is assigned to itself, so the instance does not receive a name property.

Correct:

class Student {
    constructor(name) {
        this.name = name;
    }
}

const student = new Student("Rahul");

console.log(student.name);

Output:

Rahul

Using this.name = name assigns the parameter value to the instance property.

Frequently Asked Questions

What is a constructor in JavaScript?

A constructor is a special class method that initializes a new instance. It commonly assigns initial values to the object’s properties.

Is the constructor called automatically?

Yes. When you create a class instance using new, JavaScript calls its constructor automatically.

Can a JavaScript class have multiple constructors?

No. A class can contain only one method named constructor. You can handle different initialization requirements with default parameters, optional arguments, or conditional logic.

Is a constructor required in every class?

No. If you do not define a constructor, JavaScript provides a default constructor.

What is the difference between a constructor and a method?

A constructor initializes a new instance during object creation. A regular method performs an operation and runs when you call it.

Can constructors have default parameters?

Yes. Constructors support default parameters just like other functions. These values are used when the corresponding argument is missing or undefined.

Conclusion

Constructors are an important part of JavaScript classes. They initialize new instances and allow you to assign property values when objects are created.

By understanding constructor parameters, default values, the this keyword, and the new operator, you can create objects with consistent structures and different data. Constructors work together with class methods to organize code and implement object-oriented programming in JavaScript.

1 thought on “JavaScript Constructors”

Comments are closed.