Map and Set in JavaScript

1. What is a Map?
A Map is a collection of key-value pairs, just like objects — but more powerful. However, the primary difference is that Map allows keys of any type—including functions, objects, and primitives.
const userMap = new Map();
userMap.set('name', 'Alice'); // String key
userMap.set(1, 'Admin Role'); // Number key
userMap.set({id: 1}, 'Metadata'); // Object key
2. What is a Set?
A Set is a special type of collection—"set of values" (without keys)—where each value may occur only once. If you try to add a duplicate value to a Set, it simply ignores it.
const ids = new Set();
ids.add(1);
ids.add(2);
ids.add(1); // Ignored!
console.log(ids.size); // 2
3. Map vs. Object: Why change?
While Objects are great for records, Maps are better for dynamic data storage.
Feature | Object | Map |
Key Types | Strings and Symbols only | Any type (Objects, Functions, etc.) |
Order | Not strictly guaranteed (historically) | Maintains insertion order |
Size | Manual ( | Easy |
Performance | Slower for frequent additions/removals | Optimized for frequent updates |
👉 Problem with Objects:
Keys are limited to strings
Not designed for heavy dynamic data
👉 Why Map is better:
Cleaner API (
set,get,has)More flexible keys
4. Set vs. Array: The Uniqueness Power
Arrays are ordered lists that allow duplicates. Sets are collections of unique values.
Problem with Arrays: To find if an array has a unique value, you often need
indexOforincludes, which takes $O(n)$ time.The Set Advantage: Sets are highly optimized for searching. Checking
set.has(value)is significantly faster for large datasets.
Example: Removing duplicates from an Array
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)]; // [1, 2, 3, 4, 5]
| Feature | Set | Array |
|---|---|---|
| Duplicates | Not allowed ❌ | Allowed ✅ |
| Order | Maintained ✅ | Maintained ✅ |
| Search | Faster (has) 🚀 |
Slower (includes) ⚠️ |
| Use case | Unique data | Ordered list |
5. When to use Map and Set?
Use
Mapwhen: * You need keys that aren't strings.You need to maintain the order of elements.
You are frequently adding/removing key-value pairs.
Use
Setwhen:You need to store a list where every element must be unique.
You need to perform high-performance "existence checks" (finding if an item exists).





