Map and Set in JavaScript
Okay so for a long time I was just used objects and arrays a lot for everything. If I need to store key-value pairs ? i have use Objects. if i need a list of things ? i have use Array. That's it, those were my two tools that time till i not know about Map and Set.
Then I came across Map and Set and honestly I have wondered about why nobody is talking about them more. They have solve some very specific problems that may occurs in objects and arrays and even they can't handlethem not so great.
Let me take you too through both.
The Problem with Regular Objects
Objects are seems to be perfect for storing key-value at first. And for a lot of cases they are perfect but they have some annoying quirkness in them.
Keys in an object is allowed to be only strings. If you are trying to use something else as a key like a number or another object JavaScript quietly converts it to a string behind the scenes.
const obj = {}
obj[1] = "one"
obj[2] = "two"
console.log(Object.keys(obj)) // ["1", "2"]
Your number keys has just became strings. That might not surely always matter, but sometimes it absolutely matters. also, objects aren't iterable by default in the way you want to apply a iteration on them. You can't just loop through them with for...of You need Object.keys() or Object.entries() every single time.
And there's another issue in them objects come with built-in properties inherited from their prototype. So if someone has passes a key called toString or a constructor, things can get more weird in this way.
What is Map ?
Map is a key-value store whose work is to just similar as an object but without any type of baggage in themselves.
const map = new Map();
map.set("name", "Ankur");
map.set(1, "one");
map.set(true, "yes");
console.log(map.get("name")); // Ankur
console.log(map.get(1)); // one
console.log(map.get(true)); // yes
Keys are stay fixed exactly same as you have set them. Numbers stay same as numbers. Booleans stay same as a booleans. You can even use an object as a key if you needed.
A few methods which you will use constantly nowadays:
map.set(key, value) // add or update
map.get(key) // retrieve
map.has(key) // check if key exists — returns true/false
map.delete(key) // remove a key
map.size // how many entries not.length, it's .size
And an iterating is actually in much more cleaner way:
for (const [key, value] of map) {
console.log(key, value);
}
Map vs Object
| Object | Map | |
|---|---|---|
| Key types | Strings only | Any type |
| Order guaranteed | No | insertion order |
| Easy iteration | No | Yes |
| Size | Manual | .size property |
| Prototype baggage | Yes | No |
For most simple config-style things, an object is finely used. But when your keys aren't strings, or when you need to frequently add/remove entries and check size, Map is the cleaner choice for these.
The Problem with Arrays for Uniqueness
Arrays are the great for ordered lists. But they have one big weakness in that they are allow to have duplicate in them.
const tags = ["javascript", "nodejs", "javascript", "express"]
console.log(tags.length) // 4
You've got "javascript" twice and the array doesn't care. If you want to re-duplicate this, you have to filter it down manually, and which works but feels like an extra work for something which is basic.
What is Set?
Set is a just a collection of unique values. If you are trying to add something which is already in the Set, it will simply ignores them.
const tags = new Set();
tags.add("javascript");
tags.add("nodejs");
tags.add("javascript"); // duplicate — ignored
console.log(tags.size); // 2
console.log(tags); // Set { 'javascript', 'nodejs' }
there are no duplicates, no extra filtering and no manual checking. It handles that things automatically.
Common methods are:
set.add(value) // add a value
set.has(value) // check if it exists
set.delete(value) // remove it
set.size // how many unique values
And the fastest way to re duplicate an existing array are:
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)];
console.log(unique); // [1, 2, 3, 4]
That spread operator are able to converts the Set back into an array.
Set vs Array
| Array | Set | |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Checking if value exists | .includes() | .has() |
| Order | Insertion order | Insertion order |
| Index access | Yes, arr[0] | No direct index |
| Use case | Ordered list of items | Unique collection of items |
.has() vs .includes() difference is worth noting. With an array, checking if a value exists which means looping through every element. With a Set, it's a direct lookup way faster when dealing with large collections.
When to Actually Use Them
Use Map when:
Your keys aren't strings
You need to store metadata about objects
You're adding and removing entries frequently
You need to iterate over key-value pairs in insertion order
Use Set when:
You need a collection with no duplicates
You're tracking these things like visited pages, selected items, or active tags
You want more faster existence checking with .has()
You want to re duplicate an array quickly
Practical Example
lets say you're building a feature where users can select tags for their post, and each tag should only appear once only.
const selectedTags = new Set();
selectedTags.add("javascript");
selectedTags.add("backend");
selectedTags.add("javascript"); // user clicked again
console.log(selectedTags); // Set { 'javascript', 'backend' }
there is no such type of extra logic which is needed. there is no checking if it already exists before adding. the Set just handles it on its own.
Now say you want to track which user IDs have viewed a post:
const viewers = new Map()
viewers.set(101, { name: "Ankur", viewedAt: "10:30am" })
viewers.set(102, { name: "Rahul", viewedAt: "11:00am" })
console.log(viewers.get(101)) //{name:'Ankur',viewedAt:'10:30am'}
console.log(viewers.size) // 2
Using a Map here means your keys are actual numbers, not strings which is in more cleaner and in more accurate way it has done.




