Trusted answers to developer questions

What is the super keyword in JavaScript?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The concept of super keyword comes with the idea of inheritance in JavaScript. Suppose that you have a member variable or method of the same name in the derived class as you do in the base class.

When referring to that variable/method, how would the program know if you are referring to the base class or the derived class?


This is where super comes into play. The super keyword in JavaScript acts as a reference variable to the parent class.

It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.

Let’s have a look at some examples to understand exactly how the super keyword works.

svg viewer

Code


Using super in classes

Here, super() is called to avoid duplicating the constructor parts that are common between Rectangle and Square:

class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
getName() {
console.log('Hi, I am a ', this.name + '.');
}
}
class Square extends Rectangle {
constructor(length) {
// Can't use this.height. It will throw a reference error
// It calls the parent class's constructor
super(length, length);
// In derived classes, super() must be called before you
// can use 'this'.
this.name = 'Square';
}
}

Calling super in static methods

super can also be used to call on static methods of the parent class:

class Rectangle {
constructor() {}
static getDescription() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
constructor() {
super()
}
static getDescription() {
return super.getDescription() + ' which are all equal';
}
}
console.log(Square.getDescription())

RELATED TAGS

super
javascript
inheritance
parent class
base class
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?