Creating Instances with new

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What new Actually Does

Think of a class as a rubber stamp and of each object as one print made with it. The keyword that presses the stamp is `new`. If you forget `new` and call the class like a regular function, JavaScript refuses to build anything and throws a `TypeError`:

class Codemon { constructor(name) { this.name = name; } } const zap = new Codemon("Zap"); console.log(zap.name); const broken = Codemon("Zap"); // error!

An object built from a class is called an instance of that class: `zap` is an instance of `Codemon`. Behind the scenes, `new Codemon("Zap")` does three things in a row: 1. Creates a brand-new empty object. 2. Runs the `constructor` with `this` pointing at that object, so `this.name = name` fills it in. 3. Returns the finished object, which you store in `zap`.

Exercise 2 — Checking the class

Every instance remembers the class that built it, so you can ask which blueprint it came from. The `instanceof` operator takes an object on the left and a class on the right, and answers with a boolean:

class Codemon { constructor(name) { this.name = name; } } class Item { constructor(name) { this.name = name; } } const zap = new Codemon("Zap"); const potion = new Item("Potion"); console.log(zap instanceof Codemon); console.log(potion instanceof Codemon);

`zap` and `potion` look identical — each has a single `name` property — yet they come from different blueprints. `instanceof` tells them apart when the shape alone can't: `zap instanceof Codemon` is `true`, while `potion instanceof Codemon` is `false`.

Exercise 3 — Quiz: Missing new

What happens when this code runs?

class Codemon { constructor(name) { this.name = name; } } const zap = Codemon("Zap");
Options
• An error: the class needs new
• zap holds a Codémon
• undefined
• Nothing

Hint : A class refuses to be called like an ordinary function.

Exercise 4 — Quiz: Which Class?

What does this code print?

class A {} class B {} const x = new B(); console.log(x instanceof A);
Options
• false
• true
• undefined
• An error

Hint : An instance remembers exactly which blueprint built it.

Exercise 5 — Stamp Out an Instance

Create an instance of the class and check it.

Hint : One keyword presses the stamp, one operator asks which stamp was used.

Exercise 6 — Instances in Arrays

Instances are ordinary objects, so they can go anywhere objects go: in variables, inside other objects, and of course in arrays. A team is simply an array of `Codemon` instances, and every array method you already know works on it:

class Codemon { constructor(name, level) { this.name = name; this.level = level; } describe() { return this.name + " Lv." + this.level; } } const team = [ new Codemon("Zap", 4), new Codemon("Aquachu", 12), new Codemon("Metachu", 15) ]; team.forEach((cdm) => console.log(cdm.describe())); console.log("Veterans: " + team.filter((cdm) => cdm.level >= 10).length);

`forEach` calls `describe()` on each member, and `filter` keeps only the members whose `level` is at least `10`. Going the other way is just as common. When raw data arrives from a file or a server as plain objects, `map` turns each one into a real instance with methods:

class Codemon { constructor(name, level) { this.name = name; this.level = level; } } const raw = [ { name: "Zap", level: 4 }, { name: "Aquachu", level: 12 } ]; const team = raw.map((data) => new Codemon(data.name, data.level)); console.log(team.length); console.log(team[1] instanceof Codemon);

Exercise 7 — Quiz: Instances From Data

What does this code print?

class Item { constructor(name) { this.name = name; } } const names = ["Potion", "Map", "Rope"]; const items = names.map((n) => new Item(n)); console.log(items.length + " " + items[0].name);
Options
• 3 Potion
• 3 undefined
• 1 Potion
• An error

Hint : map builds one instance per element of the source array.

Exercise 8 — Instance Cheat Sheet

Match each element with its description.

Items to match
• new Codemon("Zap")
• Codemon("Zap")
• zap instanceof Codemon
• An instance
Definitions
• Builds an instance
• An error: new is required
• true if zap was built by Codemon
• An object built from a class

Exercise 9 — Load a Team From Data

Raw data comes in as plain objects. Turn it into real Codémon instances and report on the result.

Step 1: the `Codemon` class takes a name and a level, and has a `describe()` method returning `"name Lv.X"`. Step 2: build `team` by turning every entry of `raw` into an instance. Step 3: print each instance's description, then `"All instances: X"` checking with `instanceof` that every element is a Codémon. Step 4: print `"Raw is instance: X"` checking the first raw object the same way, to show that plain data is not an instance.

Expected output:

Zap Lv.4 Aquachu Lv.12 Metachu Lv.15 All instances: true Raw is instance: false
Starter code
const raw = [ { name: "Zap", level: 4 }, { name: "Aquachu", level: 12 }, { name: "Metachu", level: 15 } ]; // Write your class here // Build and report here
Back to the course