What is inheritance in JS?

Inheritance in JavaScript means an object can use properties and methods defined on another object through the prototype chain; with classes you write it as class Child extends Parent.

How to inherit

  • Classes: extends plus super() in the constructor and super.method() to reuse parent logic.
  • Object.create(proto): create an object whose prototype is proto, without any constructor.
  • Constructor functions with manual prototype linking (legacy).

Rules for extends

  • A child constructor must call super() before using this.
  • If the child has no constructor, one is generated that passes all arguments to super.
  • Methods can be overridden; super.method() calls the parent version.
  • Static methods are inherited too.
  • You can extend built-ins (Error, Array, Map), which is common for custom error types.

Composition over inheritance

Deep inheritance trees become rigid: a change in a base class ripples everywhere, and real-world things rarely fit a single hierarchy. Modern JavaScript (and React in particular) tends to prefer composition: build objects from small pieces of behaviour, pass functions in, or use mixins. Keep inheritance shallow and use it where there is a genuine "is-a" relationship, like ValidationError extends Error.

Custom errors

class NotFoundError extends Error lets callers use instanceof NotFoundError to handle specific failures, and sets a useful name for logs.

Code example

js
1class Shape {
2 constructor(name) {
3 this.name = name;
4 }
5 area() {
6 return 0;
7 }
8 describe() {
9 return `${this.name} with area ${this.area().toFixed(2)}`;
10 }
11 static compare(a, b) {
12 return a.area() - b.area();
13 }
14}
15
16class Circle extends Shape {
17 constructor(radius) {
18 super("Circle"); // must come before using `this`
19 this.radius = radius;
20 }
21 area() {
22 return Math.PI * this.radius ** 2; // override
23 }
24}
25
26class Square extends Shape {
27 constructor(side) {
28 super("Square");
29 this.side = side;
30 }
31 area() {
32 return this.side ** 2;
33 }
34}
35
36const shapes = [new Circle(1), new Square(3), new Circle(2)];
37console.log(shapes.map((s) => s.describe()));
38console.log(shapes.toSorted(Shape.compare).map((s) => s.name)); // ["Circle", "Square", "Circle"]
39
40// Inheriting from a built-in: custom errors
41class NotFoundError extends Error {
42 constructor(resource) {
43 super(`${resource} not found`);
44 this.name = "NotFoundError";
45 }
46}
47try {
48 throw new NotFoundError("User 42");
49} catch (e) {
50 console.log(e instanceof NotFoundError, e instanceof Error, `${e}`); // true true NotFoundError: User 42 not found
51}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app