Map and Set in JavaScript

What is Map?
A Map is a collection of keyed data items, similar to an Object. However, the primary difference is that a Map allows keys of any type (strings, numbers, booleans, or even objects), whereas Object keys are typically converted to strings.
const user = { name: "Siddhartha" };
const userMetadata = new Map();
userMetadata.set(user, { lastLogin: "2026-05-01" });
console.log(userMetadata.get(user)); // Works perfectly!
What is Set?
A set is a collection of values where each value can only occur once. It is the preferred structure when you need to ensure that a list contains no duplicates.
const messyArray = [1, 2, 2, 3, 4, 4, 4, 5];
const cleanArray = [...new Set(messyArray)];
// Output: [1, 2, 3, 4, 5]
The Problem with Traditional Objects & Arrays
Before ES6, developers relied on Objects for maps and Arrays for unique lists, which led to several issues:
Object Key Constraints: Objects only support strings or symbols as keys. If you try to use an object as a key within another object, it gets converted to a string.
"[object Object]".Prototype Pollution: Objects inherit properties from their prototypes, which can lead to unintended
toString. In contrast, a Map is "clean"—it contains only the data that you explicitly add to it.Array Performance: Checking for the existence of an item in a large Array requires examining each element, resulting in a time complexity of O(n), which is slow. Sets, on the other hand, can check for item existence almost instantly, with a time complexity of O(1).
Map vs. Object
| Map | Object |
|---|---|
| Key Types of maps are Functions, Objects, etc. | Key Types of objects are strings and symbols. |
The size of the map is Built-in .size property. |
Size of object is Manual (Object.keys().length) |
| Iteration Directly iterable (forEach, for...of). | Iteration Requires Object.entries(). |
Set vs. Array
| Set | Array |
|---|---|
| Sets automatically filter them out. | Arrays allow duplicates. |
| Sets are value-based. | Arrays are indexed-based (arr[0]). |
When to use Map and Set
Use a Map when you need a dictionary where the keys can be of various types, not just strings, or when you need to frequently add or remove entries, as it performs better than objects in these situations.
Use a Set when you're working with a collection of unique items, such as tags, user IDs, or roles. A Set helps you avoid the hassle of manually checking for duplicates.


