Intermediate 8 min
Map and Set in JavaScript
A Map associates keys with values, and a Set keeps one entry per distinct value.
How it works
A membership check asks whether a value exists. An association asks which value belongs to a key. Use a Set for selected item IDs and a Map for counts by ID. Adding the same ID to a set again has no effect on which entries exist, while setting an existing map key replaces its value.
Walk through an example
A Set built from ['a', 'a', 'b'] has two entries. A Map can use an object itself as a key when identity matters.
What to watch for
Different object literals with matching properties are still different object identities. Use a stable ID if you mean to treat them as one key.
Code example
const colors = new Set(['red', 'red', 'blue']);
console.log(colors.size);Check your understanding
What number is produced?
See the example and explanation
- Worked example
- Given
new Set(['red', 'red', 'blue']).size - Answer
2
The string red appears twice but is stored once. Blue adds one more distinct entry.