Inheritance lets one class build on top of another, reusing its properties and methods instead of duplicating them. In JavaScript, this is done with the extends keyword to create a child (subclass) that inherits from a parent (superclass), and super to reach back into the parent from inside the child.
This is especially useful when several related objects share common behavior but each needs something extra or slightly different — think of a general Animal class, with Dog and Cat each adding their own specifics on top.
Using extends to Create a Subclass
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const generic = new Animal("Creature");
const dog = new Dog("Rex");
console.log(generic.speak());
console.log(dog.speak());
Output:
Creature makes a sound.
Rex barks.
Dog automatically gets everything Animal has — here it overrides speak() with its own version, which is called method overriding.
Calling the Parent Constructor with super()
If the child class defines its own constructor, it must call super(...) before using this — this runs the parent class's constructor first, so the inherited properties actually get set up.
class Dog extends Animal {
constructor(name, breed) {
super(name); // runs Animal's constructor, sets this.name
this.breed = breed;
}
speak() {
// super.speak() calls Animal's original version
return `${super.speak()} Specifically, a bark from the ${this.breed}.`;
}
}
const rex = new Dog("Rex", "Labrador");
console.log(rex.speak());
Output:
Rex makes a sound. Specifically, a bark from the Labrador.
Why This Matters
Without inheritance, you'd either copy-paste shared logic into every related class, or write one giant class trying to handle every case with conditionals. Inheritance keeps shared behavior in one place (the parent) while letting each subclass specialize only the parts that actually differ.
Inheritance builds directly on how classes work in JavaScript, so it's worth being comfortable with basic class syntax first. Under the hood, extends is just wiring together JavaScript's prototype chain for you automatically.
