Creating Maps
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Pairing Keys and Values with a Map
Imagine tracking each trainer's score during a tournament: you want to link a trainer's name (the key) to their score (the value), and look up any score in an instant. A Map is a collection designed specifically to store `key → value` pairs: 1. Create an empty Map with `new Map()`. 2. Use `.set(key, value)` to store a pair. 3. Use `.get(key)` to read the value linked to a key.
const scores = new Map();
scores.set("Sam", 120);
scores.set("Lea", 340);
console.log(scores.get("Lea"));
console.log(scores.size);Just like a Set, a Map tells you how many pairs it holds via `.size`. And if you call `.get()` with a key that doesn't exist, it simply returns `undefined`:
const scores = new Map();
scores.set("Sam", 120);
console.log(scores.get("Noa"));Exercise 2 — Updating, Checking, and Deleting Keys
Every key in a Map is unique. If you call `.set()` with a key that already exists, it updates that key's value instead of adding a duplicate entry:
const scores = new Map();
scores.set("Sam", 120);
scores.set("Sam", 500);
console.log(scores.get("Sam"));
console.log(scores.size);A Map also shares the same management methods as a Set, operating on keys: - `.has(key)` returns `true` if the key exists in the Map (or `false` otherwise). - `.delete(key)` removes the key and its value from the Map.
const scores = new Map();
scores.set("Sam", 120);
console.log(scores.has("Sam"));
scores.delete("Sam");
console.log(scores.has("Sam"));
console.log(scores.size);Exercise 3 — Creating a Map with Initial Pairs
Instead of calling `.set()` line by line, you can pass an array of `[key, value]` pairs directly into `new Map()` to populate it from the start:
const scores = new Map([
["Sam", 120],
["Lea", 340],
["Noa", 75]
]);
console.log(scores.size);
console.log(scores.get("Noa"));You can also chain `.set()` calls one after another, because each `.set()` call returns the Map itself:
const scores = new Map()
.set("Sam", 120)
.set("Lea", 340);
console.log(scores.size);Exercise 4 — Quiz: What Value?
What does this code print?
const m = new Map();
m.set("a", 1);
m.set("b", 2);
console.log(m.get("b"));21"b"undefinedHint : The key selects which value comes back.
Exercise 5 — Quiz: Set Twice
What does this code print?
const m = new Map();
m.set("a", 1);
m.set("a", 9);
console.log(m.size);1290Hint : A key can appear only once in a Map.
Exercise 6 — Record a Score
Store Sam's score, then read it back.
Hint : A Map uses one method to store a pair and another to read a value back.
Exercise 7 — Any Value Can Be a Key
Here is one of the biggest superpowers of a Map: a key doesn't have to be a string! You can use a number, a boolean, or even an object as a key. Just like a Set, a Map compares keys strictly (`===`), so the number `12` and the string `"12"` are treated as two completely different keys:
const unlocksByLevel = new Map();
unlocksByLevel.set(5, "Zap");
unlocksByLevel.set(12, "Aquachu");
console.log(unlocksByLevel.get(12));
console.log(unlocksByLevel.get("12"));You can even use a Codémon object as a key to attach extra information to it without modifying the object itself:
const cdm = { name: "Zap" };
const notes = new Map();
notes.set(cdm, "My first Codémon");
console.log(notes.get(cdm));Exercise 8 — Quiz: Number or Text Key?
What does this code print?
const m = new Map();
m.set(5, "Zap");
console.log(m.get("5"));undefined"Zap"5Hint : Keys are compared exactly, type included.
Exercise 9 — Check Before Reading
Print the score only if the trainer is recorded.
Hint : One method asks whether the key exists, the other brings the value back.
Exercise 10 — Map Cheat Sheet
Match each method with what it does.
set(k, v)get(k)has(k)get(missing)undefinedExercise 11 — Tournament Scores
Keep the tournament scores in a Map and answer the organiser's questions.
Step 1: build `scores`, a Map already holding Sam with 120, Lea with 340 and Noa with 75. Step 2: print `"Trainers: N"` with its size, then `"Lea: X"` with Lea's score. Step 3: Sam wins a match and gains 200 points: read the current score, add 200, and store it back. Print `"Sam: X"`. Step 4: Noa leaves the tournament: remove the entry. Then print `"Has Noa: X"` and `"Trainers: N"` again.
Expected output:
Trainers: 3
Lea: 340
Sam: 320
Has Noa: false
Trainers: 2// Write your code here