Skip to content
dreamcode
dreamcode
Map
Map & Set
Lesson 22 of 48
+15 XP on finish
JS COLLECTIONSChapter 4 · JS Collections Depth

Map and Set

A Set holds unique values: adding a duplicate does nothing, and .has() checks membership quickly. A Map stores key-value pairs like an object, but its keys can be any type, it remembers insertion order, and it has a .size. Use .set, .get, .has and .delete, and loop with for (const [key, value] of map).

Worked example

How it reads

  • The duplicate "vega" is ignored, so the set has 3 items
  • visits.get("Mars") + 1 reads, updates and writes back a count
  • [...new Set(array)] is the quickest way to remove duplicates
Cloud tip: Reach for a Map when keys are added and removed often, or are not strings. Plain objects are fine for fixed shapes.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Count each word with a Map, then print one line per word in the order first seen: sun 3, moon 1, star 1.

Press Run to check your work.