Invoking super class constructor without super()

Can anyone explain why the following works?

class Vehicle {
  constructor(year) {
    this.year = year;
  }
}

class Truck extends Vehicle {}

class Car extends Vehicle {}

let truck = new Truck(2003);
console.log(truck.year); // 2003

let car = new Car(2015);
console.log(car.year); // 2015

I thought it needed to be this:

class Vehicle {
  constructor(year) {
    this.year = year;
  }
}

class Truck extends Vehicle {
  constructor(year) {
    super(year);
  }
}

class Car extends Vehicle {
  constructor(year) {
    super(year);
  }
}

let truck = new Truck(2003);
console.log(truck.year); // 2003

let car = new Car(2015);
console.log(car.year); // 2015

If you don’t provide your own constructor, then a default constructor will be supplied for you. If your class is a base class, the default constructor is empty:

constructor() {}

If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided:

constructor(...args) {
  super(...args);
}
1 Like

Thank you. Just to check, you have a rest operator in the constructor parameter, and a spread operator in the super parameter right? I think of rest as gathering inputs and spread as unloading them

That’s MDN documentation, not me, but yes – you can have multiple arguments to a constructor, super (used as a function) is calling the parent constructor with zero or more arguments, which is why the docs should wait as being spread

1 Like