JavaScript · Course navigation

JavaScript Map and Set

Count values and identify distinct entries.

On this page
Before you start

Arrays, loops, and method calls.

  • Count values and identify distinct entries.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

Map stores key-value associations without the prototype-key concerns of using a plain object as an arbitrary key dictionary. Set stores unique values.

Map iteration follows insertion order. The first appearance of red precedes blue in this input, even though alphabetical order would differ.

Code example

JavaScript
const words = ["red", "blue", "red"];
const counts = new Map();
for (const word of words) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(JSON.stringify([...counts]));
console.log(new Set(words).size);
if (counts.has("green")) throw new Error("missing key");
Output
[["red",2],["blue",1]]
2

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1const words = ["red", "blue", "red"];
2const counts = new Map();
3for (const word of words) {
4 counts.set(word, (counts.get(word) ?? 0) + 1);
5}
6console.log(JSON.stringify([...counts]));
7console.log(new Set(words).size);
8if (counts.has("green")) throw new Error("missing key");

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Initialize a key-value collection.counts = []
—
Process red, then blue, then red again.counts = [[red, 2], [blue, 1]]
—
Spread entries in insertion order and serialize.counts = [[red, 2], [blue, 1]]
[["red",2],["blue",1]]
The repeated red does not increase the distinct count.unique = {red, blue}
[["red",2],["blue",1]]
2

Behind the scenes

How JavaScript processes this code

A JavaScript engine parses and runs the source. A function body runs when the function is called. console.log writes to the console.

Cost and common mistakes

The ECMAScript contract requires average sublinear access for Map; many engines use hash-based implementations. Storage is O(k) for k distinct keys.

  • Object keys are compared by identity, not by their contents.
  • Map iteration order is insertion order, not sorted order.

Try it yourself

Add green at the end.

Reveal answer and reasoning

The serialized entries append ["green",1], and the distinct count becomes 3.

Further reading