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

  1. Use Set for uniqueness: javascript const tags = new Set(["js", "css", "js"]); console.log([...tags]); // ["js", "css"] tags.add("html"); tags.delete("css");
  2. Use Map for flexible keys: javascript const cache = new Map(); const key = { id: 1 }; cache.set(key, "value"); console.log(cache.get(key)); // "value"
  3. Iterate over entries: javascript for (const [k, v] of map) { /* ... */ }

Tips

  • Set is faster than filter + indexOf for deduplication.
  • Map preserves 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.
  • Set does not deduplicate objects because each {} is a different reference.