Skip to the workspace
Pebellslearn by building
Data Structures  ›  Lesson

Map and Set

Map 12 min

javascript / Map and Set

Explore each scene at your own pace.

01 · Map and Set

Map and Set

Map and Set

Map stores key-value associations, and Set stores unique values. Both preserve insertion order when iterated.

Choose a lookup table when keys map to values, and a set when you only need membership.

See the mechanism

Walk through the modelMap and SetAuthored snapshots of the example; use Run below to test the code.
A2
A key associates with one current value.
1 of 3

Follow one example

javascript

Setting the same Map key again replaces its value; it does not add another key. Set removes repeated values, so its size is 2 and insertion order yields js,css. Object keys are compared by identity rather than by their visible fields. A plain object and a Map have different APIs; use get/set/has for a Map.

Predict, change and check

Predict: If you add "js" again after "css", does the existing tag move to the end?

Test your explanation: Try adding an existing tag, then a new one. Compare Set.size with the original array’s length.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Keyed collections answer different questions

A Map answers 'which value belongs to this key?' A Set answers 'is this value a member?' Map.set replaces the value of an existing key; Set.add does not duplicate an existing member. Their iteration order follows insertion behavior, not a default alphabetical sort.

Map keys and Set members use SameValueZero. Object keys are still compared by identity, so two separately created records do not become one member just because their fields match. Use has when an existing Map entry may legitimately contain undefined; get alone cannot distinguish that from an absent key.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.