Lesson 23 of 34 · Objects
JavaScript Map and Set
Objects and arrays can do almost anything, but JavaScript has two specialised collections that do certain jobs better: Set for collections of unique values, and Map for key-value pairs with any kind of key.
Knowing when to reach for them makes your code shorter, faster and more honest about what the data means.
Set: a collection of unique values
A Set stores each value at most once. Adding a value that's already there does nothing:
const visitors = new Set();
visitors.add("Ada");
visitors.add("Linus");
visitors.add("Ada"); // ignored: already in the set
console.log(visitors.size); // 2
console.log(visitors.has("Linus")); // true
visitors.delete("Linus");
console.log(visitors); // Set(1) { 'Ada' }
You can create a set from any array, and loop over it with for...of. Sets remember insertion order.
Removing duplicates
The most popular Set trick removes duplicates from an array in one line: build a Set, then spread it back into an array:
const drops = ["gem", "coin", "gem", "rope", "coin"];
const unique = [...new Set(drops)];
console.log(unique); // [ 'gem', 'coin', 'rope' ]
Fast membership checks
array.includes(x) checks items one by one, which gets slow for big arrays. set.has(x) is designed for exactly this question and stays fast no matter how large the set grows. If you check membership a lot, convert the array to a Set first.
Map: key-value pairs with any key
A Map is like an object built specifically for lookups. You use methods instead of dot notation:
const prices = new Map();
prices.set("potion", 10);
prices.set("sword", 150);
console.log(prices.get("potion")); // 10
console.log(prices.get("bow")); // undefined
console.log(prices.has("sword")); // true
console.log(prices.size); // 2
prices.delete("sword");
You can also create a Map from an array of pairs, or from an object with Object.entries:
const stock = new Map([["arrows", 50], ["bolts", 20]]);
const fromObject = new Map(Object.entries({ a: 1, b: 2 }));
Looping over a Map gives you [key, value] pairs, in insertion order:
for (const [item, count] of stock) {
console.log(`${item}: ${count}`);
}
Why not just use an object?
- Any key type. Object keys are always strings, while Map keys can be numbers, booleans or even objects.
map.get(1)andmap.get("1")are different entries. - Built-in size and order.
map.sizeis instant, and iteration order is guaranteed. - No surprises. Maps start empty, with no inherited keys that could collide with yours.
Use plain objects for fixed-shape records (a hero with name and level) and for JSON. Use a Map when keys are dynamic data, such as user IDs, words to count or items to cache.
Common mistakes
- Using brackets on a Map.
map["key"] = 1sets a plain property on the Map object and bypasses the Map entirely. Always usemap.setandmap.get. - Expecting JSON support.
JSON.stringify(new Map([["a", 1]]))is"{}". Convert first withObject.fromEntries(map). - Expecting Sets to compare objects by content.
new Set([{ id: 1 }, { id: 1 }])has size 2, because they're two different objects.
Assignment
Write three functions:
unique(items)returns a new array without duplicates, keeping the order in which items first appeared.unique(["fire", "ice", "fire", "wind", "ice"])→["fire", "ice", "wind"]
tallyVotes(votes)takes an array of names and returns aMapfrom each name to its number of votes.tallyVotes(["Ada", "Linus", "Ada"])→Map(2) { 'Ada' => 2, 'Linus' => 1 }
sharedItems(a, b)returns an array of the items that appear in both arrays, without duplicates, in the order they appear ina.sharedItems(["sword", "map", "gem"], ["gem", "rope", "sword"])→["sword", "gem"]
Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Maps and dictionaries in other languages
- Python Dictionaries: Keys, Values and Methods · Python
- Go Maps: Create, Read, Update, Delete and comma-ok · Go
- Java HashMap: Key-Value Pairs · Java
- C# Dictionary<TKey, TValue> · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .