Open In App

Default Constructor in JavaScript

Last Updated : 23 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a default constructor is not explicitly defined like in some other programming languages such as Java or C++. In JavaScript, objects can be created without a formal constructor.

When you create an object using the new keyword along with a constructor function, that function serves as the constructor for the object. If you don’t provide a constructor function, JavaScript still creates an object for you, and it essentially has an “invisible” default constructor.

Syntax

constructor() {}

Syntax(derived class)

constructor(...args) {
   super(...args);
}

Example 1: Here, the constructor function of the Person class initializes the properties name and age with default values. When you create an instance of Person without passing any arguments, the default values are used.

Javascript




class Person {
    constructor() {
        // Default values or optional initialization
        this.name = 'DefaultName';
        this.age = 0;
    }
 
    sayHello() {
        console.log(`Hello, my name is ${this.name}
         and I am ${this.age} years old.`);
    }
}
 
// Creating an instance
const person = new Person();
 
// Calling the method
person.sayHello();


Output

Hello, my name is DefaultName
         and I am 0 years old.

Example 2: Here, the Dog class extends the Animal class. The Dog class’s constructor uses the spread operator ...args to accept any number of arguments, and then it calls super(...args) to invoke the constructor of the superclass (Animal in this case). This allows the Dog class to initialize its own properties (breed) and inherit the properties from the Animal class (legs). The default values are used if no arguments are provided.

Javascript




class Animal {
    constructor(legs) {
        this.legs = legs;
    }
 
    displayLegs() {
        console.log(`I have ${this.legs} legs.`);
    }
}
 
class Dog extends Animal {
    constructor(...args) {
        super(...args);
        this.breed = args[0] || 'Unknown Breed';
    }
 
    bark() {
        console.log('Woof, woof!');
    }
 
    displayInfo() {
        console.log(`I am a ${this.breed}
         with ${this.legs} legs.`);
    }
}
 
// Creating an instance
const dog = new Dog(4, 'Golden Retriever');
 
// Calling methods
dog.displayLegs();
dog.bark();
dog.displayInfo();


Output

I have 4 legs.
Woof, woof!
I am a 4
         with 4 legs.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads