Map vs Object

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

▶ Do the exercises

Exercise 1 — Map vs. Object: Two Ways to Store Pairs

You already know how to store `key: value` pairs using a plain JavaScript Object (`{}`). Now you also know how to store pairs using a Map. Look at the exact same tournament scores stored both ways:

const asObject = { Sam: 120, Lea: 340 }; const asMap = new Map([["Sam", 120], ["Lea", 340]]); console.log(asObject.Sam); console.log(asMap.get("Sam"));

Both work well! Plain objects are shorter to write and are what you'll use most often to describe a single item (like a Codémon). Let's look at the key differences so you know when a Map is the better tool.

Exercise 2 — Difference 1: Objects Convert Keys to Strings

In a plain Object, property keys are always converted to strings. If you use the number `5` as a key, JavaScript silently turns it into `"5"`—so `obj[5]` and `obj["5"]` end up pointing to the exact same slot:

const obj = {}; obj[5] = "Zap"; obj["5"] = "Aquachu"; console.log(obj[5]); console.log(Object.keys(obj).length);

Because `5` became `"5"`, the second line overwrote `"Zap"` with `"Aquachu"`! A Map keeps the exact type of every key, so the number `5` and the string `"5"` stay two separate entries:

const map = new Map(); map.set(5, "Zap"); map.set("5", "Aquachu"); console.log(map.get(5)); console.log(map.size);

Exercise 3 — Difference 2: Size and Insertion Order

A Map also makes counting and ordering much simpler: 1. Counting entries: A Map gives you its count directly via `.size`, whereas an object requires extracting its keys first with `Object.keys(obj).length`. 2. Keeping order: A Map strictly preserves the exact order in which keys were added, whereas an object automatically reorders numeric keys (like `"1"`, `"2"`, `"10"`).

const obj = { Sam: 120, Lea: 340 }; const map = new Map([["Sam", 120], ["Lea", 340]]); console.log(Object.keys(obj).length); console.log(map.size);

Exercise 4 — When to Use an Object vs. a Map

Here is a simple rule of thumb to choose between an Object and a Map: Use an Object (`{}`) when: 1. You are describing a single item with fixed properties (like a Codémon's `name`, `type`, and `level`). 2. You know all the property names in advance when writing your code.

Use a Map (`new Map()`) when: 1. Entries are added and removed dynamically while your program runs. 2. Your keys are numbers, booleans, or objects instead of plain strings. 3. You frequently need to check `.size` or preserve the exact order in which entries were added.

// A single Codémon with fixed properties -> Object const myCdm = { name: "Zap", type: "Electric", level: 5 }; // A live scoreboard where trainers join and leave -> Map const leaderboard = new Map(); leaderboard.set("Sam", 120); leaderboard.set("Lea", 340); console.log(myCdm.name); console.log(leaderboard.get("Lea"));

Exercise 5 — Quiz: The Overwritten Key

What does this code print?

const obj = {}; obj[1] = "a"; obj["1"] = "b"; console.log(Object.keys(obj).length);
Options
• 1
• 2
• 0
• An error

Hint : Think about what type an object's keys always are.

Exercise 6 — Quiz: The Map Version

What does this code print?

const m = new Map(); m.set(1, "a"); m.set("1", "b"); console.log(m.size);
Options
• 2
• 1
• 0
• An error

Hint : A Map compares keys exactly, type included.

Exercise 7 — Count Both Ways

Print how many pairs each collection holds.

Hint : An object is measured through a helper that lists what it contains, a Map knows its own count.

Exercise 8 — Quiz: Which Would You Use?

You store one Codémon with a `name`, a `type` and a `level`. Which fits best?

Options
• An object: fixed properties known in advance
• A Map: the keys change all the time
• A Set: it refuses duplicates
• An array: it keeps the order

Hint : Ask whether the keys are decided by you now, or created while the program runs.

Exercise 9 — Map vs Object

Match each statement with the collection it describes.

Items to match
• Keys are always text
• Keys can be numbers or objects
• Counted with .size
• Counted with Object.keys()
Definitions
• Object
• Map
• Map
• Object

Exercise 10 — Level Registry

The game groups Codémon by level. Because the levels are numbers, a Map is the right tool: an object would turn every level into text.

Step 1: build `registry`, a Map whose keys are the numbers 5, 12 and 20, with the values `"Zap"`, `"Aquachu"` and `"Metachu"`. Step 2: print `"Levels: N"` with its size, then `"Level 12: X"` with the value stored at that key. Step 3: prove the keys really are numbers by printing `"Text key 12: X"`, reading the key `"12"` written as text. Step 4: a Codémon reaches level 30: add the pair, then print `"Levels: N"` and `"Has level 5: X"`.

Expected output:

Levels: 3 Level 12: Aquachu Text key 12: undefined Levels: 4 Has level 5: true
Starter code
// Write your code here
Back to the course