When developing with classes in JavaScript, you often come across the super keyword. In this blog post, let’s explore the purpose and usage of super.

Let’s start with a simple example. We have a class called Car:

class Car {
 constructor() {
 console.log('This is a car');
 }
}

The constructor method in a class is special because it is executed when the class is instantiated. For example:

const myCar = new Car(); //'This is a car'

Now, let’s say we have a class called Tesla that extends the Car class:

class Tesla extends Car {

}

The Tesla class inherits all the methods and properties of the Car class, including the constructor method. So, when we create an instance of the Tesla class, it will execute the Car class constructor as well:

const myCar = new Tesla();

If we want to override the constructor method in the Tesla class, we can do so:

class Tesla extends Car {
 constructor() {
 console.log('This is a Tesla');
 }
}

Now, when we create a Tesla object, it will display 'This is a Tesla' instead.

const myCar = new Tesla(); //'This is a Tesla'

In the constructor method, we can also invoke the same method in the parent class using super(). This allows us to perform the logic of the parent class constructor before adding additional logic:

class Tesla extends Car {
 constructor() {
 super();
 console.log('This is a Tesla');
 }
}

Now, when we create a Tesla object, both the Car class constructor and the Tesla class constructor will be executed:

const myCar = new Tesla();
//'This is a car'
//'This is a Tesla'

Keep in mind that super() can only be called within the constructor and not in other methods. Additionally, if the parent constructor accepts parameters, you can pass them in when using super().

To summarize, the super keyword in JavaScript classes allows us to call and extend the functionality of the parent class constructor.