What are Set and Map in JavaScript, and when do you use them over objects and arrays?
Quick Answer
Set holds unique values — great for de-duplication ([...new Set(arr)]) and fast membership checks. Map is a key/value collection where keys can be any type (not just strings), it keeps insertion order, has a real .size, and iterates cleanly — better than a plain object for a dynamic dictionary.
Set is a collection of unique values, so the quick way to de-dupe an array is [...new Set(arr)], and checking membership is O(1) versus array.includes being O(n). Map is a proper dictionary — the keys can be objects, not just strings, it remembers insertion order, it has a size property, and it iterates without you dealing with prototype keys. So for a dynamic lookup I use a Map; for a fixed-shape record or something I'm going to JSON.stringify, a plain object is still right.
Set.has()/Map.get()are O(1); an arrayincludes()is O(n).- Object keys are coerced to strings and you inherit prototype keys;
Mapavoids both. WeakMap/WeakSethold weak references — entries are GC'd when the key object has no other references (caches, private data).- Objects still win for fixed-shape records and JSON.