JavaScript Map & Set — Modern Data Structures Explained

What is a Map?
👉 A Map is a collection of key-value pairs
Just like objects, but more powerful
Example
const user = new Map()
user.set("name", "Rohan")
user.set("age", 22)
console.log(user.get("name")); // Rohan
Key Features of Map
Keys can be any type (not just strings)
Maintains insertion order
Easy methods (
set,get,has,delete)
What is a Set?
👉 A Set is a collection of unique values
Example
const numbers = new Set([1, 2, 2, 3, 4])
console.log(numbers); // {1, 2, 3, 4}
👉 Duplicate values are automatically removed
Key Features of Set
Stores only unique values
No index-based access
Useful for removing duplicates
⚖️ Map vs Object
| Feature | Map 🗂️ | Object 📦 |
|---|---|---|
| Key Types | Any type | String / Symbol |
| Order | Maintained | Not guaranteed (older JS) |
| Performance | Better for large data | Good for simple use |
| Built-in Methods | Yes | Limited |
⚖️ Set vs Array
| Feature | Set 🔹 | Array 📚 |
|---|---|---|
| Duplicate Values | Not allowed | Allowed |
| Order | Maintained | Maintained |
| Access | No index | Index-based |
| Use Case | Unique data | Ordered list |
Problems with Objects & Arrays
❌ Objects
Keys limited to strings
No built-in iteration methods (older style)
❌ Arrays
Allow duplicates
Manual filtering needed
When to Use Map & Set
✅ Use Map when:
You need key-value pairs with flexibility
Keys are not strings
Frequent add/remove operations
✅ Use Set when:
You need unique values
Removing duplicates
Checking existence quickly
Real-World Examples
1️⃣ Remove Duplicates
const arr = [1, 2, 2, 3];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3]
2️⃣ Store Dynamic Data
const map = new Map();
map.set({ id: 1 }, "User1");
👉 Objects as keys 😎
Final Thoughts
👉 Map & Set are modern, powerful alternatives to:
Objects
Arrays
They help you:
Write cleaner code ✨
Improve performance ⚡
Solve problems efficiently 🧠


