Hold data by key, or as a set

INPUT · Slides

Map, which holds key and value pairs

01 / 06

Objects are hard to count

You already know one other container that holds key and value pairs: the object.

But objects have something they are bad at. How many entries are in there right now does not come out plainly. .length belongs to arrays, so it does not work, and with data whose keys come and go, this quietly becomes a nuisance.

02 / 06

Make a Map and add pairs

Write new Map() and you get a container that holds key and value pairs. The same writing as making a real thing with new in the classes chapter.

  • set(key, value) … put a pair in
  • get(key) … take the value from the key
  • size … how many pairs there are now

size takes no (). Like .length, it is a shape that takes the value out as it is.

const scores = new Map();scores.set("Yui", 80);scores.set("Haruto", 65);console.log(scores.get("Yui"));console.log(scores.size);

Result

80
2

03 / 06

Check whether it is there, and delete it

has(key) answers "is that key there" with true / false. delete(key) removes one pair.

Add, take, check, delete. That what you want to do is the method name as it stands is what makes Map readable. With an object, you often cannot remember how to write the deleting.

const scores = new Map();scores.set("Yui", 80);console.log(scores.has("Yui"));scores.delete("Yui");console.log(scores.has("Yui"));console.log(scores.size);

Result

true
false
0

04 / 06

Showing it as it is shows nothing

Worth knowing up front. Hand a Map straight to console.log and the contents do not come out. The way this course shows things, you only get {}.

When you want to check the contents, do this.

  • show size to see the count
  • show the result of get to see one
  • show one pair at a time with for...of
const scores = new Map();scores.set("Yui", 80);console.log(scores);console.log(scores.size);

Result

{}
1

05 / 06

What comes out is a pair

When you go round with for...of, what comes out of a Map is a pair, [key, value]. The value does not come out as it is, the way it did going round an array.

So write destructuring where you catch it. Then you can give the key and the value separate names and use them.

const scores = new Map();scores.set("Yui", 80);scores.set("Haruto", 65);for (const [name, score] of scores) {  console.log(`${name} scored ${score}`);}

Result

Yui scored 80
Haruto scored 65

06 / 06

Choosing between an object and a Map

With both around, you wonder which to use. Roughly this is the guide.

  • the entry names are settled in advance … an object (for a person, name and age, settled)
  • the keys are not known until it runs … a Map (scores per person, and other moving names)

When you want to count entries or delete a pair, a Map writes more plainly too. Right — let us make one.