Map and Set in JavaScript
Modern Data Structure You Should Actually Use

Introduction
JavaScript already has:
Object
{}for key value pairsArrays
[]for lists
So why do we need Map and Set?
Because sometimes:
Objects are limited
Arrays allows duplicates
Code becomes messy
That's where map and set shine.
What is a Map?
A map is a collection of key-value pairs, just like an object -- but more powerful.
Example:
const userMap = new Map();
userMap.set("name", "Tony");
userMap.set("age", 24);
console.log(userMap.get("name")); // Tony
Key Features of Map
Any type can be a key (not just strings)
Maintains insertion order
Built-in methods like
.set(),.get(),.has()
What is a Set?
A set is a collection of unique values.
No duplicates allowed.
Example:
const numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // duplicate
console.log(numbers); // {1, 2}
Map vs Object
| Feature | Object | Map |
|---|---|---|
| Key types | String/Symbol | Any type |
| Order | Not guaranteed | Maintained |
| Iteration | Complex | Easy for...of |
| Performance | Good | Better for large data |
Problem With Objects
const obj = {};
obj[true] = "yes";
obj[1] = "one";
console.log(obj);
Keys get converted into string --> unexpected behavior
Map Solves This
const map = new Map();
map.set(true, "yes");
map.set(1, "one");
console.log(map);
Keys remain their original type
Set vs Array
| Feature | Array | Set |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Maintained | Maintained |
| Methods | Many | Simple |
Problems with Arrays
const nums = [1, 2, 2, 3];
const unique = [...new Set(nums)];
console.log(unique); // [1, 2, 3]
You need extra logic to remove duplicates
Set Handles it Automatically
const nums = new Set([1, 2, 2, 3]);
console.log(nums); // {1, 2, 3}
When to Use Map?
Use Map when:
You need key value pairs
Keys are not just strings
You care about insertion order
Frequent add/remove operations
Why to Use Set?
Use set when:
You need unique values
You want to remove duplicates
You don't care about indexing
Real World Use cases
Map:
Storing user data with IDs
Caching result
Tracking objects relationships
Set:
Removing duplicates from arrays
Tracking unique visitors
Filtering unique values
Suggestion for Learning
1. Start replacing objects
try using map instead of {} in some cases
2. Use set for uniqueness
Anytime you see duplicates --> think set
3. Practice conversion
Array --> Set --> Array
Object --> Map
4. Keep it Practical
Don't use Map/Set everywhere, use them when needed.
Final Thoughts
Map = Powerful key-value storage
Set = Unique value collection
They solve real problems that:
Objects
Arrays
can't handle cleanly.



