JavaScript Subclasses: extends, super, Overriding Methods and Extending Built-ins
Inheritance with class extends: the super() call and its rules, overriding methods and calling super.method(), inherited static methods, polymorphism, new.target and abstract base classes, the overridden-method-in-constructor trap, custom Error classes, and subclassing Array and Map safely.
kvi5hnuCode Sprout team member6 min readOn this page
A subclass is a more specific version of an existing class: a Circle is a kind of Shape, a ValidationError is a kind of Error, an AdminUser is a kind of User. The subclass inherits everything the parent (the superclass) does and can add new members or replace (override) existing ones. JavaScript's extends and super keywords make this straightforward.
extends
class Shape {
constructor(name) {
this.name = name;
}
area() {
return 0;
}
describe() {
return `${this.name} with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(radius) {
super("circle"); // run Shape's constructor first
this.radius = radius;
}
area() { // override
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super("rectangle");
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const shapes = [new Circle(1), new Rectangle(2, 3)];
for (const s of shapes) console.log(s.describe());
console.log(shapes[0] instanceof Circle, shapes[0] instanceof Shape);
circle with area 3.14
rectangle with area 6.00
true true
describe is written once, in Shape, yet calls the right area for each object. That's polymorphism: the same method call (this.area()) does different things depending on the object's actual class, because method lookup starts at the instance and walks up the prototype chain, finding the most specific version first.
What extends sets up

class Circle extends Shape creates two prototype links (article 70):
Circle.prototypeinherits fromShape.prototype, so instances get Shape's methods.Circleitself inherits fromShape, so static methods are inherited too.
class Shape {
static create(...args) {
return new this(...args); // this is the class the method was called on
}
}
class Circle extends Shape {
constructor(r) {
super();
this.r = r;
}
}
console.log(Object.getPrototypeOf(Circle.prototype) === Shape.prototype);
console.log(Object.getPrototypeOf(Circle) === Shape);
console.log(Circle.create(5) instanceof Circle);
true
true
true
Circle.create(5) runs Shape's static method with this set to Circle, so it creates a Circle. That's why static factories should use new this(...) rather than naming the class.
Before class existed, setting up a subclass took several error-prone lines (Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; plus calling Super.call(this, ...) in the constructor), and statics weren't inherited at all. You'll still see that pattern in older code.
super() in constructors
A subclass constructor must call super(...) before it uses this or returns, because in a derived class it's the superclass constructor that actually creates the object:
class Base {
constructor(label) {
this.label = label;
}
}
class ThisTooEarly extends Base {
constructor() {
this.x = 1; // before super()
super("x");
}
}
class ForgotSuper extends Base {
constructor() {}
}
for (const C of [ThisTooEarly, ForgotSuper]) {
try {
new C();
} catch (err) {
console.log(C.name, err.name);
}
}
class NoConstructor extends Base {}
console.log(new NoConstructor("auto").label);
ThisTooEarly ReferenceError
ForgotSuper ReferenceError
auto
The rules:
- If a subclass defines a constructor, it must call
super(...)exactly once, before touchingthis. - If a subclass has no constructor, one is created automatically that passes all arguments through:
constructor(...args) { super(...args); }. - Code that doesn't use
this(like validating arguments) may run beforesuper(). - The subclass's fields are initialized right after
super()returns, before the rest of the constructor runs.
Overriding methods and super.method()
A subclass method with the same name as a superclass method overrides it. To extend the parent's behavior rather than replace it, call the parent's version with super.method(...):
class Shape {
constructor(name) { this.name = name; }
area() { return 0; }
describe() { return `${this.name} with area ${this.area()}`; }
}
class Rectangle extends Shape {
constructor(w, h) {
super("rectangle");
this.w = w;
this.h = h;
}
area() { return this.w * this.h; }
describe() {
return `${super.describe()} (${this.w}x${this.h})`; // parent's version + more
}
}
console.log(new Rectangle(2, 3).describe());
rectangle with area 6 (2x3)
super.describe() runs the parent's method with the same this, so inside it, this.area() still finds Rectangle's area. You can call super methods anywhere in a method, before, after or in the middle of your own code, and it works through any number of levels:
class Animal { speak() { return "..."; } }
class Dog extends Animal { speak() { return "Woof"; } }
class Puppy extends Dog { speak() { return `${super.speak()}!`; } }
class Shy extends Dog { static greet() { return "hides"; } }
console.log(new Puppy().speak(), Shy.greet(), new Shy().speak());
Woof! hides Woof
super also works in static methods (calling the parent class's static method) and even in object-literal methods (article 52).
Abstract base classes and new.target
JavaScript has no abstract keyword, but you can get the same effect. Inside a constructor, new.target is the class that new was actually called on, which, in a superclass constructor, is the subclass:
class Repository {
constructor() {
if (new.target === Repository) {
throw new TypeError("Repository is abstract; extend it");
}
}
findById(id) {
throw new Error(`${this.constructor.name} must implement findById()`);
}
exists(id) { // shared logic built on the abstract method
return this.findById(id) !== undefined;
}
}
class MemoryRepository extends Repository {
#items = new Map([[1, { id: 1, name: "Ana" }]]);
findById(id) {
return this.#items.get(id);
}
}
class IncompleteRepository extends Repository {}
try {
new Repository();
} catch (err) {
console.log(err.message);
}
console.log(new MemoryRepository().exists(1), new MemoryRepository().exists(2));
try {
new IncompleteRepository().exists(1);
} catch (err) {
console.log(err.message);
}
Repository is abstract; extend it
true false
IncompleteRepository must implement findById()
This is the template method pattern: the base class implements the general algorithm (exists) and leaves specific steps (findById) to subclasses. TypeScript adds real abstract classes and methods, checked before the code runs (part 17).
The overridden-method-in-constructor trap
When a superclass constructor calls a method that a subclass overrides, the subclass version runs before the subclass's own fields are initialized:
class Widget {
constructor() {
this.render(); // calls the subclass's render...
}
render() {}
}
class Label extends Widget {
text = "Hello"; // ...but this field isn't set yet
render() {
console.log("rendering:", this.text);
}
}
new Label();
rendering: undefined
Fields of Label are initialized only after super() (Widget's constructor) returns. Avoid calling overridable methods from constructors, or give the subclass an explicit initialization step that runs later.
Custom error classes
Extending Error is one of the most useful kinds of subclassing. It lets callers distinguish error types with instanceof and attach extra data:
class ValidationError extends Error {
constructor(field, message, options) {
super(message, options); // options can include { cause }
this.name = "ValidationError";
this.field = field;
}
}
function parseAge(text) {
const age = Number(text);
if (!Number.isInteger(age) || age < 0) {
throw new ValidationError("age", `Invalid age: "${text}"`);
}
return age;
}
try {
parseAge("ten");
} catch (err) {
if (err instanceof ValidationError) {
console.log(err.name, err.field, err.message);
console.log(String(err), err instanceof Error);
} else {
throw err;
}
}
ValidationError age Invalid age: "ten"
ValidationError: Invalid age: "ten" true
Set name so that messages and stack traces show the right type. Pass { cause } through to super to keep the original error when wrapping one (article 44). A common alternative is setting name once with a class field: name = "ValidationError";.
Extending built-in classes
Built-ins like Array, Map, Set and Error can be extended, and the instances behave like real built-in objects:
class Stack extends Array {
peek() {
return this.at(-1);
}
}
const stack = Stack.from([1, 2, 3]); // inherited static method
console.log(stack.peek(), stack.length, Array.isArray(stack));
console.log(stack.map((x) => x * 2) instanceof Stack); // map returns a Stack too
3 3 true
true
Note that array methods such as map, filter and slice return instances of the subclass (they use this.constructor via Symbol.species), which can surprise you if your subclass constructor expects different arguments.
Overriding a built-in method lets you add rules, such as type checks in a Map:
class TypedMap extends Map {
#keyType;
#valueType;
constructor(keyType, valueType, entries = []) {
super(); // start empty...
this.#keyType = keyType;
this.#valueType = valueType;
for (const [k, v] of entries) this.set(k, v); // ...then add through our checks
}
set(key, value) {
if (typeof key !== this.#keyType || typeof value !== this.#valueType) {
throw new TypeError(`Expected ${this.#keyType} -> ${this.#valueType}`);
}
return super.set(key, value);
}
}
const scores = new TypedMap("string", "number", [["ana", 90]]);
scores.set("bo", 85);
try {
scores.set("cy", "95");
} catch (err) {
console.log(err.message);
}
console.log(scores.size, scores instanceof Map);
Expected string -> number
2 true
Why not pass entries to super(entries)? The Map constructor adds initial entries by calling this.set, which is our override, and at that moment the private fields don't exist yet (they're created after super() returns), so it would throw a TypeError. Starting empty and adding entries afterward avoids the problem. This is the same trap as the previous section, in a built-in.
Common questions
Does JavaScript support multiple inheritance?
No. A class extends at most one class, because each object has a single prototype. To combine behavior from several sources, use composition or mixins (next article).
Can I override a field or a getter?
Yes. A subclass field with the same name creates an own property that shadows the parent's. Getters and setters override like methods, but if you override only the getter, the inherited setter is hidden too, so define both.
What does super refer to in a method?
The prototype of the object where the method was defined (its "home object"), not of this. So super.method() always means "the parent class's version," even when this is a deeper subclass instance.
Can a class extend null or an expression?
extends accepts any expression that evaluates to a constructor, which is how mixins work: class A extends withLogging(Base) {}. extends null is technically allowed but almost never useful.
Summary
class B extends Amakes B's instances inherit A's methods and B itself inherit A's static methods.- A subclass constructor must call
super(...)before usingthis; without a constructor, arguments are passed through automatically. - Overriding replaces a method;
super.method()calls the parent's version with the samethis. Method lookup finds the most specific override first (polymorphism). new.targetlets a base class refuse direct instantiation; throwing "must implement" errors marks abstract methods.- A superclass constructor that calls an overridden method sees the subclass's fields uninitialized.
- Extend
Error(setname, passcause) for meaningful error types; extendingArrayandMapworks, but mindSymbol.speciesand constructors that call overridden methods.
Practice Questions
What does this print?
class A {
hi() {
return "A";
}
}
class B extends A {
hi() {
return super.hi() + "B";
}
}
class C extends B {} console.log(new C().hi());
Answer
AB. C inherits B's hi, which calls A's hi through super and appends "B".
Why does this code fail when instantiated?
class P extends Array {
constructor() {
this.tag = 1;
super();
}
}
Answer
It uses this before calling super(). In a derived class, the object doesn't exist until the superclass constructor creates it, so accessing this first throws a ReferenceError.
Write a NotFoundError class that extends Error, sets name, and stores a resource property.
Answer
class NotFoundError extends Error {
constructor(resource, options) {
super(`${resource} not found`, options);
this.name = "NotFoundError";
this.resource = resource;
}
}
What does this print?
class A {
static make() {
return new this();
}
}
class B extends A {} console.log(B.make() instanceof B, A.make() instanceof B);
Answer
true false. Static methods are inherited, and this in make is whichever class it was called on.
Previous: JavaScript Classes: class Syntax, Constructors, Methods, Fields, Static Members and Private #fields
Next: Composition over Inheritance in JavaScript: Delegation, Mixins and Abstract Classes

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.