Understanding Map and Set in JavaScript
When working with JavaScript, we usually start with objects and arrays to store data.
They work fine in most cases.
But as things grow, some limitations start showing up.
That’s where Map and Set come in.
They solve specific problems that objects and arrays don’t handle well.
Why Not Just Use Objects and Arrays?
Objects store data as key-value pairs.
Arrays store data as ordered lists.
But there are problems:
Objects only allow string or symbol keys
Arrays allow duplicates even when you don’t want them
Managing uniqueness or special key types becomes messy
Map and Set were introduced to fix these issues.
What is a Map?
A Map is a collection of key-value pairs, similar to an object.
But the difference is important.
In a Map:
keys can be any type (not just strings)
order is preserved
it’s designed specifically for key-value storage
Example:
const map = new Map()
map.set("name", "Ishan")
map.set(1, "number key")
console.log(map.get("name"))
Here, keys are not limited to strings. That’s the main advantage.
What is a Set?
A Set is a collection of values.
But unlike arrays:
It only stores unique values
Example:
const set = new Set([1, 2, 2, 3])
console.log(set)
Output:
{1, 2, 3}
The duplicate 2 is automatically removed.
Map vs Object
At first, Map looks like an object. But they behave differently.
Object:
keys are converted to strings
not designed specifically for key-value operations
Map:
keys can be any type (number, object, etc.)
better for dynamic key-value data
has built-in methods like
.set(),.get()
Simple way to think:
Object = general-purpose
Map = specialized key-value storage
Set vs Array
Arrays allow duplicates.
Example:
[1, 2, 2, 3]
Set removes duplicates automatically.
Example:
new Set([1, 2, 2, 3])
So:
Array = ordered list
Set = unique values only
When Should You Use Map?
Use Map when:
keys are not just strings
you need reliable key-value storage
data is dynamic
Example:
storing user data with complex keys
caching values
When Should You Use Set?
Use Set when:
you need unique values
you want to remove duplicates easily
Example:
filtering duplicate numbers
tracking unique items
One Simple Way to Remember
Map → key-value storage
Set → unique values
Conclusion
Map and Set are not replacements for objects and arrays. They are improvements for specific use cases.
When used correctly, they make code cleaner and easier to manage.
The key is knowing when to use them, not just how they work.