The volunteers at the Elm Street toy library lend toys from a garage, and they want a tracker that knows what’s on the shelves. Their toys aren’t all alike, though. A building set has a brick count, and a dress-up box has a size, but every toy has an ID, a name, and a minimum age.
In this lesson, you’ll write a Toy class for what every toy shares, then use extends to build on it for each kind of toy. Each kind adds only what makes it different. You’ll also learn a quick test for when that’s the right tool.
Start From What Every Toy Shares
This course assumes you can already write a class with a constructor, methods, and a private # field, and import code from another file. You’ll build the tracker as Node scripts with a current version of Node.js, a terminal, and your editor.
You’ll type and run the code in the text lessons. The videos show what JavaScript does behind the scenes, and each section ends with an exercise on the site that tests your code.
Over the course, the tracker grows from kinds of toy to a lending desk that lends them safely, explains why a loan fails, and reads what volunteers type. The course ends with a fuller toy library that you build from a brief, then an invitation to plan a program of your own.
Make a folder called toy-library and open a terminal in it. The fields every toy has go in one class. Save this as toy.js:
toy.js
export class Toy {
#minAge;
constructor(id, name, minAge) {
this.id = id;
this.name = name;
this.#minAge = minAge;
}
static fromRecord(record) {
return new Toy(record.id, record.name, record.minAge);
}
suitsAge(age) {
return age >= this.#minAge;
}
describe() {
return `${this.id}: ${this.name} (ages ${this.#minAge}+)`;
}
}
Most of this is a class you already know how to write. The minimum age is a safety rule, so you store it in the private field #minAge, and outside code asks .suitsAge() instead. .describe() gives the volunteers one line per toy.
The new keyword is static. A static method belongs to the class itself, so you call it on the class, as you already call Object.entries() on Object. The volunteers keep their toys as saved records, and Toy.fromRecord(record) turns one record into a real Toy. Save this as toys.js:
toys.js
import { Toy } from "./toy.js";
const train = new Toy("T01", "Wooden train set", 3);
console.log(train.describe());
console.log("Suits Leo (4):", train.suitsAge(4));
const record = { id: "T03", name: "Dress-up box", minAge: 4 };
const box = Toy.fromRecord(record);
console.log(box.describe());
console.log("On a toy:", train.fromRecord);
Run it:
$ node toys.js
T01: Wooden train set (ages 3+)
Suits Leo (4): true
T03: Dress-up box (ages 4+)
On a toy: undefined
The last line shows undefined because .fromRecord() isn’t on the train. It’s a static method, so you call it on Toy itself. That’s all you need about static for now.
The dress-up box has a size, though, and Toy has nowhere to put one. You could copy the code from toy.js to make a DressUp class, then copy it again for building sets. However, you’d then have to make every fix to the shared part two or three times.
Build Kinds of Toy With extends and super
You want a class that starts with everything Toy has and adds to it. That’s what extends does. The class after extends is the parent class, and the new class is a subclass that inherits the parent’s methods. You’ll build up one subclass, a building set, starting from a class that adds nothing to Toy.
Start With an Empty Subclass
A subclass with nothing of its own shows what extends alone gives you. Save this as building-set.js:
building-set.js
import { Toy } from "./toy.js";
export class BuildingSet extends Toy {}
BuildingSet has an empty body, with no constructor. Save this as sets.js to make a building set with it:
sets.js
import { BuildingSet } from "./building-set.js";
const bricks = new BuildingSet("T02", "Building set", 8);
console.log(bricks.describe());
console.log("Suits Priya (9):", bricks.suitsAge(9));
console.log("Suits Maya (6):", bricks.suitsAge(6));
Before you run it, predict what happens. The class has no constructor, so where do the ID, the name, and the age go?
$ node sets.js
T02: Building set (ages 8+)
Suits Priya (9): true
Suits Maya (6): false
It works. A subclass without a constructor gets one that JavaScript writes for it, which passes every argument to the parent’s constructor. So the constructor in Toy stored all three values, and the methods came from Toy too.
Give a Kind Its Own Data
A building set needs a constructor of its own to store its brick count. Inside it, super() calls the parent’s constructor. Replace the empty braces in building-set.js with a body:
building-set.js
import { Toy } from "./toy.js";
export class BuildingSet extends Toy {
constructor(id, name, minAge, brickCount) {
super(id, name, minAge);
this.brickCount = brickCount;
}
bagsNeeded() {
return Math.ceil(this.brickCount / 250);
}
}
The constructor hands the three shared values to Toy with super(id, name, minAge), then stores the one value only building sets have. The new .bagsNeeded() method tells the volunteers how many bags to set out, at 250 bricks a bag. Math.ceil() rounds any fraction up to a whole number and leaves whole numbers as they are, so 1,000 bricks need 4 bags, and 1,001 need 5.
Watch out for the order: super() must run before any line that uses this, because in a subclass the new object doesn’t exist until the parent’s constructor has made it. Otherwise, JavaScript stops with a ReferenceError: “Must call super constructor in derived class before accessing ‘this’ or returning from derived constructor”.
If it seems odd that this isn’t ready in a constructor, the button below opens a mentor chat with this question typed in for you to send or change:
Extend a Parent’s Method With super
A building set should also describe itself with its brick count. A method with the same name as a parent’s method is an override. A BuildingSet then uses its own .describe() instead of the one in Toy.
You don’t want to throw the Toy class’s description away, only to add to it. Inside a method, super.describe() calls the parent’s version, so the override can extend it. Add this method to BuildingSet, after .bagsNeeded():
describe() {
return `${super.describe()}, ${this.brickCount} bricks`;
}
It takes the Toy class’s line from super.describe() and adds the brick count. You’ll run it in a moment, on a shelf with every kind of toy.
building-set.js
import { Toy } from "./toy.js";
export class BuildingSet extends Toy {
constructor(id, name, minAge, brickCount) {
super(id, name, minAge);
this.brickCount = brickCount;
}
bagsNeeded() {
return Math.ceil(this.brickCount / 250);
}
describe() {
return `${super.describe()}, ${this.brickCount} bricks`;
}
}
Why not write the whole sentence in BuildingSet, ages and all? It can’t. A subclass can’t use its parent’s # fields, so this.#minAge inside BuildingSet is a SyntaxError.
The private name only exists inside the braces of Toy. A subclass reaches private data through the parent’s public methods, such as super.describe() or .suitsAge().
The dress-up box follows the same pattern, with a size instead of a brick count. Try writing DressUp in dress-up.js before you open the answer. Its constructor takes the three shared values first, then the size, so that new DressUp("T03", "Dress-up box", 4, "medium") works, and its .describe() adds text such as ", size medium".
dress-up.js
import { Toy } from "./toy.js";
export class DressUp extends Toy {
constructor(id, name, minAge, size) {
super(id, name, minAge);
this.size = size;
}
describe() {
return `${super.describe()}, size ${this.size}`;
}
}
Now put all three kinds on one shelf. Save this as shelf.js:
shelf.js
import { Toy } from "./toy.js";
import { BuildingSet } from "./building-set.js";
import { DressUp } from "./dress-up.js";
const bricks = new BuildingSet("T02", "Building set", 8, 1000);
const shelf = [
new Toy("T01", "Wooden train set", 3),
bricks,
new DressUp("T03", "Dress-up box", 4, "medium"),
];
for (const toy of shelf) {
console.log(toy.describe());
}
console.log("Bags for T02:", bricks.bagsNeeded());
Run it:
$ node shelf.js
T01: Wooden train set (ages 3+)
T02: Building set (ages 8+), 1000 bricks
T03: Dress-up box (ages 4+), size medium
Bags for T02: 4
The loop makes the same call on every toy, and each line comes out right for its kind. The shared part comes from one place, so if the volunteers want “ages 3 and up” instead of “ages 3+”, you’d change Toy alone.
Ask Whether It Really Is a Toy
extends saved you from copying Toy, so it’s tempting to use it whenever two classes share some code. That’s not what it’s for. Before you write extends, say “a ___ is a ___” out loud, and use extends only when the sentence is true. Try it on the tracker’s classes:
- “A building set is a toy.” True. Everything that’s true of a toy is true of a building set, so
BuildingSet extends Toyfits. So doesDressUp. - “A member is a toy.” False. Maya Chen has a name and an age, but she can’t be lent out, and
.suitsAge()makes no sense on her. Sharing a field or two doesn’t make one a kind of the other. - “A loan is a toy.” False. A loan has a toy and a member who borrowed it. That’s a different relationship, with a tool you’ll meet later in this course.
When the sentence is true, every method of the parent makes sense on the subclass.
To practice the test on things that aren’t toys, ask the mentor for a few pairs to judge:
Check Your Understanding
These questions check that you can write a subclass and decide when extends fits:
1. The library gets kites. In kite.js, write a Kite class that extends Toy with a line length in feet, a .describe() method that adds text such as ", 50 ft line" to the Toy class’s line, and a .needsLongString() method that returns true for a line over 30 feet. Make kite "T04", a "Rainbow kite" for ages 6 and up with a 50-foot line, and log its description.
2. Which of these should extend Toy: a ToyBox class that holds several toys, a PuppetSet class with a number of puppets, or a Volunteer class with a name and the days they help?
1. The constructor calls super() first, and .describe() builds on super.describe():
kite.js
import { Toy } from "./toy.js";
export class Kite extends Toy {
constructor(id, name, minAge, lineFeet) {
super(id, name, minAge);
this.lineFeet = lineFeet;
}
needsLongString() {
return this.lineFeet > 30;
}
describe() {
return `${super.describe()}, ${this.lineFeet} ft line`;
}
}
To try it, save this as kites.js:
kites.js
import { Kite } from "./kite.js";
const kite = new Kite("T04", "Rainbow kite", 6, 50);
console.log(kite.describe());
console.log("Long string:", kite.needsLongString());
The kite’s line starts with the Toy class’s text and ends with its own:
$ node kites.js
T04: Rainbow kite (ages 6+), 50 ft line
Long string: true
2. Only PuppetSet, because “a puppet set is a toy” is true. A toy box has toys, so it isn’t one. A volunteer has a name but is a person.
The tracker now has a Toy and two kinds of toy that add their own data and extend .describe(). However, when the loop calls toy.describe(), how does JavaScript pick which .describe() runs, and where does super.describe() look? Next, in Follow a Method Up the Chain, you’ll watch that lookup happen one step at a time.