Skip to the content

super()

JavaScript · Unit 13: Inheritance

If the child needs one more piece of data, it writes its own constructor. But before storing its own things, it calls the parent's with super(...): it passes what the parent needs, and the parent stores it.

class Animal {
  constructor(name) {
    this.name = name;
  }
}
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}
const d = new Dog("Rex", "pug");
console.log(d.name, d.breed);

Prints

Rex pug

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so Chef's constructor passes the name on to Employee's.

  3. 3. Find the bug

    This program should print "Kira 7". Which line has the bug?

  4. 4. Multiple choice

    In a child's constructor, why does super(...) go before any this.something = ...?

  5. 5. Predict the output

    Both constructors print something. What comes out?

  6. 6. Predict the output

    What does this code print?

  7. 7. Find the bug

    This program should print "Kia 4". Which line has the bug?

  8. 8. Put the lines in order

    A password needs 8 letters. Put in order the program that creates the error for one with 5, and prints its message and how many are missing.

  9. 9. Find the case that fails

    measure(a, b) returns the area of an a by b rectangle. If you only give it one side, it uses a Square, and the area should be side times side. Which call makes it fail?

  10. 10. Predict the output

    Mia opens a payroll account and her salary comes in. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →