After this lesson you can remove duplicates in one line, check membership quickly, and use a Map when a plain object is the wrong tool. Both come built into JavaScript, with no imports needed.
Set: a collection with no duplicates
A Set holds values and refuses to hold the same one twice.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const tags = new Set();
tags.add("html");
tags.add("css");
tags.add("html"); // ignored, already present
log("size:", tags.size);
log("has css?", tags.has("css"));
tags.delete("css");
log("after delete:", [...tags].join(","));
const nums = [3, 1, 3, 2, 1];
const unique = [...new Set(nums)];
log("unique:", unique.join(","));
</script>The Set reports a size of 2, says true for css, then holds only html. The deduplicated array is 3,1,2: the Set remembers the order of first insertion. The methods to know are add, has, delete, clear and the size property.
Why use a Set rather than an array with includes? Checking set.has(x) is designed to stay fast even for large collections, while array.includes(x) checks items one by one. For a handful of items it makes no difference; with thousands, a Set is the better fit.
A Set treats NaN as equal to itself, unlike ===. Objects are compared by reference, so two separate objects with identical contents both stay in the Set.
Sets are iterable, so for (const tag of tags) works. Newer JavaScript also has set operations such as union and intersection, but they arrived recently and are not in all browsers yet, so check support before relying on them. A reliable alternative is a filter: [...a].filter(x => b.has(x)) gives the items in both.
Map: key and value pairs with any key
A Map is like an object, but with these differences:
- Keys can be any type: numbers, objects, even functions. Object keys are always strings or symbols.
- It remembers insertion order for all keys.
- It has a size property and a clean API with no inherited keys to worry about.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const ages = new Map();
ages.set("Asha", 25);
ages.set("Ben", 31).set("Chen", 28); // set returns the map, so calls chain
log("size:", ages.size);
log("Ben:", ages.get("Ben"));
log("Dev:", String(ages.get("Dev"))); // missing key
log("has Chen?", ages.has("Chen"));
ages.delete("Chen");
for (const [name, age] of ages) {
log(name, "is", age);
}
</script>Looping gives [key, value] pairs, which you can destructure as you read in destructuring. map.keys(), map.values() and map.entries() give iterators. You can build a Map from entries, new Map([["a", 1], ["b", 2]]), and convert one back with Object.fromEntries(map) or to an array with [...map].
An object key
Here is the case an ordinary object cannot handle:
const first = { id: 1 };
const second = { id: 2 };
const notes = new Map();
notes.set(first, "important");
notes.set(second, "later");
console.log(notes.get(first)); // important
const plain = {};
plain[first] = "important";
plain[second] = "later";
console.log(Object.keys(plain)); // [ '[object Object]' ] both collapsed into one keyWith a plain object both keys turn into the text "[object Object]" and overwrite each other. That is a real bug you can avoid with a Map.
Counting with a Map
A very common job is counting how many times each value appears:
const words = ["red", "blue", "red", "green", "red"];
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts); // Map(3) { 'red' => 3, 'blue' => 1, 'green' => 1 }The ?? 0 supplies a starting value when the word has not been seen yet. (A plain object would do the job here as well; see the objects lesson. The Map becomes the better choice when keys come from user data and might be names like constructor or toString.)
Map or object?
Pick an object for a fixed record with known property names, such as a user with name and age, and when you want to write it as JSON. Pick a Map when:
- keys are not known in advance (a dictionary, a cache, a tally),
- keys are not strings,
- you add and remove entries often, or need a reliable size.
Maps and Sets do not convert to JSON directly (JSON.stringify(new Map()) gives {}), so turn them into arrays first, as covered in JSON.
WeakMap and WeakSet
You may see WeakMap and WeakSet. They hold objects without stopping the browser from cleaning them up and cannot be looped over. They are for specialist cases such as attaching private data to objects; you can ignore them for now.
Common mistakes
- Using bracket syntax on a Map,
map["key"] = 1. It sets an ordinary property, not an entry. Usemap.set. - Using
lengthinstead ofsize. It givesundefined. - Expecting a Set to compare object contents. Two equal-looking objects are different values.
- Trying to print a Map with
JSON.stringifyand getting{}. - Modifying a Set while looping over it in ways that add items endlessly.
Exercise
Given const letters = ["a", "b", "a", "c", "b", "a"], produce an array with no duplicates, then use a Map to count each letter and print the counts, one per line.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const letters = ["a", "b", "a", "c", "b", "a"];
log("unique:", [...new Set(letters)].join(","));
const counts = new Map();
for (const letter of letters) {
counts.set(letter, (counts.get(letter) ?? 0) + 1);
}
for (const [letter, count] of counts) {
log(letter, count);
}
</script>Next: dates and time.
Key points
- A Set stores unique values. Adding a value that is already there does nothing.
- new Set(array) is the quickest way to remove duplicates, and [...set] turns it back into an array.
- A Map stores key and value pairs like an object, but keys can be any type and it remembers insertion order.
- Use size, not length, and methods like add, has, delete, get and set instead of bracket access.
- Choose a Map when keys are not fixed names, change often, or are not strings.