Skip to content

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 my free JavaScript Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about js: