Technology · JavaScript
JavaScript Set and Map
Work with collections using Set and Map, understand key differences, and common use cases.
TL;DR
- 01Use Set to store unique values and check membership quickly.
- 02Use Map for key-value pairs with any type as the key.
- 03Both are iterable with for-of and have size properties.
Set Basics
- Create a Set to store unique values of any type.
const numbers = new Set([1, 2, 2, 3, 3, 3]); console.log(numbers); // Set { 1, 2, 3 } - Use
add()to insert values into the set.const colors = new Set(); colors.add("red"); colors.add("blue"); - Use
has()to check if a value exists in the set.colors.has("red"); // true colors.has("green"); // false - Use
delete()to remove a value andclear()to empty the set.colors.delete("red"); colors.clear(); - Use
sizeto get the number of unique values in the set.
Map Basics
- Create a Map to store key-value pairs with any type of key.
const user = new Map(); user.set("name", "Alice"); user.set("age", 30); - Use
set()to add or update entries in the map.const config = new Map([ ["timeout", 5000], ["retries", 3] ]); - Use
get()to retrieve values by their key.config.get("timeout"); // 5000 - Use
has()to check if a key exists without retrieving the value.config.has("timeout"); // true - Use
delete()andclear()to remove entries or empty the map.
Set vs Object
- Set stores unique values, while object keys are always strings or symbols.
const set = new Set([1, "1", 1]); // Set { 1, "1" } const obj = {}; obj[1] = "number"; obj["1"] = "string"; // obj only has one key "1" with value "string" - Set uses
has()for membership checking, objects useinoperator. - Set automatically prevents duplicates, objects do not.
- Use Set when you only care about unique values without keys.
- Use Map or object when you need to associate values with keys.
Map vs Object
- Map can use any type as a key, objects only use strings or symbols.
const map = new Map(); map.set({x: 1}, "object key"); map.set(() => {}, "function key"); const obj = {}; obj[{x: 1}] = "converts key to string"; - Map preserves insertion order, objects mostly do but with quirks.
- Map has a
sizeproperty, objects requireObject.keys()to count. - Map is optimized for frequent additions and deletions.
const cache = new Map(); cache.set(userId, userData); - Use Map when keys are not strings or for better performance.
Iteration and Conversion
- Iterate over a Set using
for-oforforEach().const numbers = new Set([1, 2, 3]); for (const n of numbers) console.log(n); numbers.forEach(n => console.log(n)); - Iterate over a Map with
for-ofto get [key, value] pairs.const user = new Map([["name", "Alice"], ["age", 30]]); for (const [key, value] of user) console.log(key, value); - Convert Set to Array using the spread operator.
const arr = [...new Set([1, 2, 2, 3])]; // [1, 2, 3] - Convert Map to Array of entries or use
.entries(),.keys(),.values().const entries = [...user.entries()]; const keys = [...user.keys()]; const values = [...user.values()];
Tip: Use Set to remove duplicates from an array quickly with the spread operator:
[...new Set(array)].
Warning: Map keys are compared by reference, not value, so
new Map().set({}, 1).get({})returns undefined since the objects are different.