How to use Set and Map in JavaScript
· Category: JavaScript
Short answer
Set stores unique values of any type. Map stores key-value pairs where keys can be any type, including objects, and maintains insertion order.
Steps
- Use Set for uniqueness:
javascript const tags = new Set(["js", "css", "js"]); console.log([...tags]); // ["js", "css"] tags.add("html"); tags.delete("css"); - Use Map for flexible keys:
javascript const cache = new Map(); const key = { id: 1 }; cache.set(key, "value"); console.log(cache.get(key)); // "value" - Iterate over entries:
javascript for (const [k, v] of map) { /* ... */ }
Tips
Setis faster thanfilter+indexOffor deduplication.Mappreserves insertion order and has better performance than plain objects for frequent additions and removals.
Common issues
- Objects used as keys in Maps are compared by reference, not by content.
Setdoes not deduplicate objects because each{}is a different reference.