The JavaScript super keyword
When we work with classes in JavaScript, it’s common to use the super keyword.
In this post I want to clarify what’s it useful for.
Suppose you have a class Car:
class Car {
}and in this class we have a constructor() method:
class Car {
  constructor() {
    console.log('This is a car')
  }
}The constructor method is special because it is executed when the class is instantiated:
const myCar = new Car() //'This is a car'You can have a Tesla class that extends the Car class:
class Tesla extends Car {
}The Tesla class inherited all the methods and properties of Car, including the constructor method.
We can create an instance of the Tesla class, creating a new myCar object:
const myCar = new Tesla()And the original constructor in Car is still executed, because Tesla does not have one of its own.
We can override the constructor() method in the Tesla class:
class Tesla extends Car {
  constructor() {
    console.log('This is a Tesla')
  }
}and
const myCar = new Tesla()will print This is a Tesla .
In the constructor() method we can also call super() to invoke the same method in the parent class:
class Tesla extends Car {
  constructor() {
    super()
    console.log('This is a Tesla')
  }
}Calling
const myCar = new Tesla()will now execute 2 console logs. First the one defined in the Car class constructor, the second the one defined in the Tesla class constructor:
'This is a car'
'This is a Tesla'Note that super() can only be called in the constructor, not in other methods.
And we can pass in any parameter, if the constructor accepts parameters.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.