Map and Set in JavaScript 🔑

Introduction
In JavaScript, we often use objects and arrays to store data.
But sometimes, they come with limitations like:
Objects only allow string/symbol keys
Arrays allow duplicate values
Managing data efficiently becomes tricky
To solve these problems, JavaScript introduced two powerful data structures:
Map and Set.
What is Map?
A Map is a collection of key-value pairs, just like objects,but more powerful.
Key Features:
Keys can be any data type (not just strings)
Maintains insertion order
Easy size tracking
Example:
let map = new Map();
map.set("name", "Shrutika");
map.set(1, "Number Key");
map.set(true, "Boolean Key");
console.log(map.get("name")); // Shrutika
Visual Idea :
What is Set?
A Set is a collection of unique values.
That means no duplicates allowed
Key Features:
Stores only unique values
Maintains insertion order
Works with any data type
Example:
let set = new Set();
set.add(10);
set.add(20);
set.add(10); // duplicate
console.log(set); // {10, 20}
Visual Idea :
~Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key Type | Any data type | Only string/symbol |
| Order | Maintained | Not guaranteed (older JS) |
| Size | .size |
No direct method |
| Iteration | Easy | Complex |
Example Problem with Object:
let obj = {};
obj[1] = "one";
obj["1"] = "string one";
console.log(obj); // Only one value remains!
Object converts keys into strings → causes conflict
~Set vs Array
| Feature | Set | Array |
|---|---|---|
| Duplicates | Not allowed | Allowed |
| Performance | Faster for checking | Slower |
| Index | No index | Has index |
Example Problem with Array:
let arr = [1, 2, 2, 3];
console.log(arr); // duplicates exist
Set solves this easily:
let unique = new Set(arr);
console.log(unique); // {1, 2, 3}
When to Use Map?
Use Map when:
You need key-value storage
Keys are not just strings
You need fast lookup
Example:
Storing user data
Caching results
Mapping IDs to objects
When to Use Set?
Use Set when:
You want unique values only
You need to remove duplicates
You want fast existence checks
Example:
Removing duplicates from arrays
Tracking visited items
Storing unique IDs
Conclusion
Map is best for storing structured key-value data
Set is best for handling unique collections
Both solve limitations of traditional objects and arrays



