Map and Set in JavaScript
Understanding Map and Set

What is Map
A Map is a special collection of key-value pairs in JavaScript. It is very similar to a standard object, but it is much more flexible because it allows you to use absolutely any data type as a key.
Think of a Map like a highly advanced physical locker system. In a standard locker (an object), you can only use a standard metal key (a string) to open your door. In this advanced locker system (a Map), your key could be a fingerprint, a passcode, or even another physical object.
const userMap = new Map();
userMap.set("name", "Rahul");
userMap.set(1, "ID");
Here is a step-by-step breakdown of how this works
We initialize a new Map collection using
new Map().We use the
.set()method to store data. First, we use a standard string"name"as the key, and map it to the value"Rahul".We use
.set()again, but this time we use a literal number1as the key, mapping it to the string"ID".
Why Not Just Use Objects
What problem does Map actually solve? Traditional objects have strict limitations. In a standard object, keys are almost always converted to strings behind the scenes. If you try to use a number or another object as a key, JavaScript will force it into a string. Furthermore, objects do not guarantee the exact order of your properties, and they lack a built-in way to easily count how many items they hold. Map solves all of these flexibility issues.
What is Set
A Set is a collection of completely unique values. It can store any type of data, but a specific value can only exist exactly one time inside the collection.
Think of a Set like a VIP guest list at a private event. If someone tries to write down the exact same guest name twice, the security team ignores the second attempt. Duplicates are strictly not allowed on the list.
const ids = new Set([1, 2, 2, 3]);
console.log(ids); // Output: Set(3) { 1, 2, 3 }
Let us look at what JavaScript is doing step-by-step
We create a new Set and pass in an array of numbers that includes a duplicate.
JavaScript looks at the first
1and the first2and adds them to the collection.It sees the second
2, realizes it is a duplicate of a value that already exists, and completely removes it.It adds the
3, leaving us with a collection of only unique values.
Practical Understanding
Difference: Map vs Object
When should we actually use a Map instead of an Object? It comes down to three main differences:
Key types: Objects only allow strings and symbols as keys. Maps allow anything, including numbers, arrays, or even entire objects.
Ordering: Maps always remember the exact historical order in which you inserted your items. Objects do not strictly guarantee this.
Usability: Maps have a convenient built-in
.sizeproperty to instantly check how many items exist. Objects require you to manually count the keys.
Difference: Set vs Array
Arrays and Sets look similar, but their behaviors are entirely different
Duplicates allowed vs not: Arrays gladly accept duplicate values. Sets automatically reject and remove them.
Indexing vs no indexing: Arrays are ordered by index numbers, meaning you can grab the first item using
array[0]. Sets do not have indexes. You cannot access a Set item by its position.
Practical Use Cases
When to use Map
Storing user data where the user ID is a strict number, not a string.
Caching data or API responses where the search query object itself is used as the key.
Dynamic key storage where keys are added and removed frequently, as Maps perform better in these scenarios.
When to use Set
Removing duplicates from a messy list of data retrieved from a database.
Tracking unique visitor IDs on a webpage to ensure you do not count the same person twice.
Validation checks to see if a specific tag or permission already exists in a list.
Practical Example
Let us look at the most common real-world use case for a Set: cleaning up an array.
const users = ["A", "B", "A"];
const uniqueUsers = new Set(users);
console.log([...uniqueUsers]); // Output: ["A", "B"]
Here is the step-by-step explanation
We start with a standard array that contains a duplicate user
"A".We pass that entire array into a new Set, which instantly filters out the duplicate.
Because Sets do not have indexes, we use the spread operator
...inside square brackets to unpack those unique values back into a fresh, usable array.
Common Mistakes
When learning Map and Set, beginners often run into a few specific traps
Using Map when an object is enough: If your keys are just simple strings and you are not doing complex additions or deletions, stick to a plain object. Keep your code simple.
Expecting Set to behave like an array: Beginners often try to read a Set using index notation like
mySet[0]. This will returnundefined. Sets are used for checking if a value exists, not for reading by position.Forgetting the correct methods: You cannot use standard object dot notation to add items. Map requires
.set(),.get(), and.has(). Set requires.add(),.has(), and.delete().
Summary
Map stores key-value pairs and allows highly flexible keys of any data type.
Set stores only unique values and automatically discards any duplicates.
Choosing Map vs Object depends entirely on whether you need flexible key types and guaranteed ordering.
Choosing Set vs Array depends entirely on whether your data requires strict uniqueness.
In the next article, we will explore string polyfills and common interview methods in JavaScript.




