Map and Set in JavaScript
Mastering Map and Set in JavaScript

Hi, I’m Abdul Samad. A web development learner and tech enthusiast. I write about what I learn, share practical coding tips, and publish in-depth blogs on programming and modern web development.
Check out my full collection of blogs on Hashnode: https://abdulsamad30.hashnode.dev/
Connect with me on X for quick updates and insights: @abdul_sama60108
JavaScript gives you objects and arrays out of the box.
They work. But at some point, you'll run into situations where they feel like the wrong tool for the job too rigid, too unpredictable, or just plain annoying to work with. That's exactly where Map and Set come in.
Let's break them down properly.
What is a Map?
A Map is a collection of key-value pairs similar to an object, but without the baggage.
The key difference?
In a Map, any value can be a key: strings, numbers, objects, even other maps.
Think of it like a contact list where each person's phone number is stored against their actual name. The "name" is your key, the "phone number" is your value.
You look someone up by their name, and you get their number back.
const contacts = new Map();
contacts.set("Ali", "0300-1234567");
contacts.set("Sara", "0321-9876543");
contacts.set("Ahmed", "0312-5556789");
console.log(contacts.get("Sara")); // "0321-9876543"
console.log(contacts.size); // 3
Output:
0321-9876543
3
You add entries with .set(), retrieve them with .get(), and check the count with .size. Clean and straightforward.
What is a Set?
A Set is a collection of unique values. No duplicates allowed if you try to add the same value twice, it just gets ignored. The Set handles it silently.
Every item in a Set is distinct. If you've seen a value before, it stays out.
const tags = new Set();
tags.add("javascript");
tags.add("webdev");
tags.add("javascript"); // duplicate — ignored
tags.add("nodejs");
console.log(tags); // Set(3) { 'javascript', 'webdev', 'nodejs' }
console.log(tags.size); // 3
Output:
Set(3) { 'javascript', 'webdev', 'nodejs' }
3
The duplicate "javascript" never makes it in. The Set enforces uniqueness automatically no manual checks needed.
Map vs Object
Objects seem like the natural choice for key-value storage. And they work fine until they don't.
The problems with plain objects:
Keys are always coerced to strings. Pass a number or an object as a key, and JavaScript quietly converts it to a string which leads to unexpected behavior.
Objects come with inherited properties from their prototype. If you're not careful, keys like
toStringorconstructorcan clash with built-in properties.Checking the number of entries requires a workaround (
Object.keys(obj).length). There's no.sizeproperty.Iteration order isn't guaranteed for non-string keys in older environments.
Map solves all of this.
const obj = {};
const map = new Map();
const keyObj = { id: 1 };
obj[keyObj] = "value from object";
map.set(keyObj, "value from map");
console.log(obj["[object Object]"]); // "value from object" — key got stringified
console.log(map.get(keyObj)); // "value from map" — key preserved as-is
Output:
value from object
value from map
With the object, the key { id: 1 } got converted to the string "[object Object]". With Map, the actual object reference is used as the key. No silent conversion.
| Feature | Object | Map |
|---|---|---|
| Key types | Strings/Symbols only | Any value |
| Key order | Not fully guaranteed | Insertion order guaranteed |
| Size check | Object.keys(obj).length |
map.size |
| Prototype clashes | Possible | None |
| Iteration | Manual | Built-in (forEach, for...of) |
Set vs Array
Arrays are ordered lists. You can push the same value multiple times, and the array will happily hold all copies. That's useful when you need duplicates but a real problem when you don't.
The problem with arrays for uniqueness:
To check if a value already exists before inserting, you'd use includes() or indexOf() which scans the entire array every time. On large datasets, that's slow.
// Array — allows duplicates
const arr = [1, 2, 3, 2, 1];
console.log(arr); // [1, 2, 3, 2, 1]
// Set — enforces uniqueness
const set = new Set([1, 2, 3, 2, 1]);
console.log(set); // Set(3) { 1, 2, 3 }
Output:
[1, 2, 3, 2, 1]
Set(3) { 1, 2, 3 }
Set also gives you faster lookups. .has() on a Set is O(1). includes() on an array is O(n). For large collections, that difference matters.
| Feature | Array | Set |
|---|---|---|
| Allows duplicates | Yes | No |
| Lookup speed | O(n) | O(1) |
| Order | Index-based | Insertion order |
| Use case | Ordered lists | Unique collections |
When to Use Map and Set
Use Map when:
You need keys that aren't strings (numbers, objects, etc.)
You're frequently adding and deleting entries
You need to track how many entries you have without calculating it
You want clean, reliable iteration over key-value pairs
// Counting word frequency — Map is perfect for this
const text = "the cat sat on the mat the cat";
const freq = new Map();
for (const word of text.split(" ")) {
freq.set(word, (freq.get(word) || 0) + 1);
}
console.log(freq.get("cat")); // 2
console.log(freq.get("the")); // 3
Output:
2
3
Use Set when:
You need a list of unique values
You want to remove duplicates from an array quickly
You need fast membership checks
// Removing duplicates from an array
const ids = [1, 2, 3, 2, 4, 1, 5];
const uniqueIds = [...new Set(ids)];
console.log(uniqueIds); // [1, 2, 3, 4, 5]
Output:
[1, 2, 3, 4, 5]
That one-liner [...new Set(arr)]is one of the most useful patterns in JavaScript. Converts to Set (removes duplicates), spreads back into an array. Done.
Wrapping Up
Map and Set aren't replacements for objects and arrays across the board they're the better choice in specific situations.
If you need reliable key-value storage with non-string keys or frequent mutations, reach for Map.
If you need a collection where every item must be unique, reach for Set.
Once you start using them, you'll notice how often a plain object or array was actually the wrong tool. These two structures fill real gaps that come up in everyday JavaScript development.
FIN ✌️




