The super Keyword

The super keyword in JavaScript is used to access and call functions on an object's parent class. It is primarily used within class inheritance to call methods or constructors from the superclass.

Illustration of the_super_keyword
Illustration of the_super_keyword

💡 What is super?

super allows a subclass to access properties and methods of its parent class, enabling code reuse and method extension.

Using super in a constructor

When extending a class, you must call super() inside the subclass constructor before using this. This calls the parent class constructor.

📌 Deep Dive: Calling Parent Constructor

JAVASCRIPT
class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);          // Call parent constructor
    this.breed = breed;
  }
}

const myDog = new Dog('Max', 'Golden Retriever');
console.log(myDog.name);  // Output: Max
console.log(myDog.breed); // Output: Golden Retriever
Output
Max
Golden Retriever

Using super to call parent methods

Within subclass methods, super.methodName() calls the parent class method, allowing you to extend or customize behavior.

📌 Deep Dive: Calling Parent Methods

JAVASCRIPT
class Animal {
  speak() {
    return 'Animal makes a sound';
  }
}

class Dog extends Animal {
  speak() {
    const parentSound = super.speak();  // Call parent method
    return parentSound + ' and Dog barks';
  }
}

const myDog = new Dog();
console.log(myDog.speak());  // Output: Animal makes a sound and Dog barks
Output
Animal makes a sound and Dog barks

⚠️ Important Usage Note

You must call super() before accessing this in a subclass constructor. Omitting it causes a ReferenceError.

Summary: super Usage
ContextPurpose
ConstructorCall parent class constructor to initialize inherited properties
MethodsCall parent class methods to extend or reuse behavior

Key points to remember:

  • super() calls the parent constructor.
  • super.method() calls a method from the parent class.
  • Use super only in classes that extend another class.
  • Always call super() before using this in constructors.

💡 Why use super?

It enables subclasses to build upon and reuse the functionality of their parent classes, promoting cleaner and more maintainable code.