Menu
Coddy logo textTech

Using super

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 37 of 56.

When you override a method, you can still access the parent's original version using super.methodName(). This lets you extend or modify parent behavior instead of completely replacing it.

Create a parent class with a method:

class Animal {
  makeSound() {
    return "Generic animal sound";
  }
}

Create a child class that extends the parent:

class Dog extends Animal {
  makeSound() {
    // Call the parent's method first
    const parentSound = super.makeSound();
    // Then extend with additional functionality
    return `${parentSound}, but also Woof!`;
  }
}

Create an instance of the child class:

const myDog = new Dog();
console.log(myDog.makeSound());
// Output: "Generic animal sound, but also Woof!"

The super keyword allows you to call the parent class's methods while still adding your own functionality in the child class.

challenge icon

Challenge

You're given a Shape class with a calculateArea() method and a Rectangle class that extends it. Your task is to override the calculateArea() method in Rectangle using super.

Your task is to complete the calculateArea() method in the Rectangle class to:

  1. Call the parent's calculateArea() method using super and store the result
  2. Calculate the rectangle's actual area: width × height
  3. Return a combined string: parent's message + rectangle area. Example: Calculating area... Rectangle area: 50

Cheat sheet

Use super.methodName() to access the parent class's original method when overriding:

class Animal {
  makeSound() {
    return "Generic animal sound";
  }
}

class Dog extends Animal {
  makeSound() {
    const parentSound = super.makeSound();
    return `${parentSound}, but also Woof!`;
  }
}

const myDog = new Dog();
console.log(myDog.makeSound());
// Output: "Generic animal sound, but also Woof!"

This allows you to extend parent functionality instead of completely replacing it.

Try it yourself

import { Shape } from './shapes.js';
import { Rectangle } from './shapes.js';

// Test code - do not modify
const rectangle = new Rectangle(5, 10);
console.log(rectangle.calculateArea()); // Expected: "Calculating area... Rectangle area: 50"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming