Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.7 — Inheritance with extends and super
JavaScript · Example 3 of 4

Extending built-ins: a custom Error and an Array

map on a Stack returns a Stack: built-in array methods create new results using the subclass. The custom error keeps the message and stack trace from Error.

class Child extends Parent makes a class that starts with everything Parent has and adds or changes parts; super(...) runs the parent's constructor, super.method() calls the parent's version of a method you override, and instanceof checks the whole family line.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write class Vehicle with constructor(wheels) and describe() returning "A vehicle with N wheels", and class Bike extends Vehicle that passes 2 to super and overrides describe() to add " and a bell" using super.describe().

02

Write class NotFoundError extends Error that takes a resource name, sets the message to "<resource> not found", sets name, and stores status = 404. Throw and catch it, and log the error and its status.

03

Write class SortedList extends Array with an add(value) method that inserts the value and keeps the array sorted ascending (numbers). Add 5, 1, 3 and log the array with Array.from.

Explain it without notes

01

What does class B extends A set up, in terms of prototypes?

02

Why must a subclass constructor call super() before using this?

03

How do you override a method but still use the parent's behaviour?

04

What is the construction order of a subclass instance, and what bug can it cause?

Extending built-ins: a custom Error and an Array

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

ValidationError: Email needs an @
true true email
3 3 true
true