Set and Map provide purpose-built collections with better semantics than plain objects for many tasks. Interview questions often involve deduplication and frequency counting.
Common Interview Questions
Q: When use Map over Object?
Answer: When keys are non-strings (objects, functions), you need guaranteed insertion order, frequent size checks, or better iteration ergonomics without prototype pollution.
Q: Deduplicate an array
Answer: Set keeps only unique values using SameValueZero equality. NaN is considered equal to itself in Set.
const unique = [...new Set(arr)];
Q: Count character frequencies
Answer: Map.get/set with nullish coalescing is cleaner than object key coercion issues.
function charCount(str) {
const map = new Map();
for (const ch of str) {
map.set(ch, (map.get(ch) ?? 0) + 1);
}
return map;
}
Q: WeakMap vs Map for caches?
Answer: Map holds keys strongly — can leak memory. WeakMap allows GC when key objects are otherwise unreachable — good for DOM metadata.
Key Points for Interviews
-
Set: unique values; Map: key-value any type
-
Objects coerce keys to strings — Map does not
-
Map maintains insertion order (objects mostly do now too)
-
Spread Set for dedupe is idiomatic ES6+
-
O(1) average get/set for interview complexity questions
