CHAPTER 9 · 2 lessons · 26 exercises
Hold data by key, or as a set
Hold key-value pairs with `Map`, and build a collection with no duplicates using `Set`. The containers you reach for after arrays and objects.
You have learnt two containers for holding values together so far: the array, which holds by order, and the object, which holds by name. This chapter adds two more, for the scenes that are awkward in either.
The first is Map. Like an object it holds "key and value pairs", but several of its natures differ. The most useful is that the count comes straight out. How many entries are in an object cannot be counted plainly, but with a Map you get it from size. That adding, taking, deleting and checking are all provided as methods reads well too.
The other is Set. This one is a collection with no duplicates. However many times you add the same value, it folds into one. Wanting to strip duplicates out of an array turns out to happen often, and that is where it shows its worth. The order is kept, but you cannot take things out by number. Think of it as a container for handling "there or not".
The guide for choosing is this. If the entry names are settled in advance, an object (for a person, name and age, settled). If the keys are not known until it runs, a Map (scores per person, and so on). If you only want to hold there-or-not, a Set.
Both are made with new. The same writing as the instances you made in the classes chapter. Think of them as classes JavaScript has prepared for you and it settles easily.
One thing to note: showing a Map or a Set as it is does not show the contents. The way this course shows things, you only get {}. When you want to check the contents, show the count, show them one at a time with for...of, or spread them into an array and show that. This chapter's exercises are written that way too.
There is no need to force them in where arrays and objects are enough. But they turn up perfectly normally in other people's code, and when you meet a scene where you want the duplicates gone, whether you remember Set changes the amount of code you write completely.
Lessons in this chapter
Map and Set
- 86Map, which holds key and value pairsMake a
new Map()and add, take and count key and value pairs.Go to the exercises - 87Set, a collection with no duplicatesUse
new Set()to build a collection where the same value cannot go in twice.Go to the exercises