Map and Set in JavaScript

What is a Map?
A Map is a collection of keyed data items, similar to an Object. However, the primary difference is that Map allows keys of any type functions, objects, or even primitives.
Map vs Object
Feature | Object | Map |
Key Types | String or Symbol only | Any type (Objects, Funcs, etc.) |
Order | Not reliably ordered | Maintains insertion order |
Size | Manual calculation |
|
Performance | Better for small, static data | Better for frequent adds/removes |
What is a Set?
A Set is a collection of values where each value must be unique. Think of it as an Array with a built-in "no duplicates" policy.
The Power of Uniqueness
The most common use case for a Set is instantly cleaning an array. If you have a list of user IDs with duplicates, you can wipe them out in one line:
const uniqueIds = [...new Set([1, 2, 2, 3, 4, 4])]; // [1, 2, 3, 4]
Set vs. Array
Search Speed: Checking if an item exists in an Array (
arr.includes(x)) takes O(n) time. In a Set (set.has(x)), it is O(1). If you have 10,000 items, the Set is orders of magnitude faster.No Duplicates: Arrays allow you to push the same value a million times. Sets silently ignore duplicates, keeping your data clean automatically.
When to reach for Map and Set
Use a Map when:
You need keys that aren't strings (e.g., associating metadata with a DOM element).
You need to frequently add and remove key-value pairs (Maps are optimized for this).
You need to iterate over data in the exact order it was added.
Use a Set when:
You are dealing with a list where duplicates are logically impossible or unwanted (like a list of "Liked" posts).
You need to perform high-speed "existence checks" (checking if a username is already taken in a local list).






