Skip to content
Arrays & ObjectsChapter 26 / 47Intermediate5 min read

Map & Set

Learn what JavaScript Map and Set are, how they differ from objects and arrays, unique values, any-type keys, Map.groupBy, and the new Set methods.

On this page

1. What are Map & Set?

Object keys can only be strings or symbols. In a Map, the key can be a number, an object, even a function, and it remembers insertion order.

Set is like an array but does not allow duplicate values. A value is either in the set or it is not.

2. Why does it matter?

Objects and arrays are not perfect for every job. For lookups that are added and removed often, and for unique lists, Map and Set are better and faster.

Making do with objects / arraysWith Map / Set
Object keys turn into stringsIn a Map, the key keeps its real type
Object.keys().length for the sizemap.size directly
filter and indexOf to remove duplicatesUnique in one line with new Set
includes scans the whole arrayset.has is a fast lookup

3. Where is it used?

SituationWhat to use
Unique tags, categories, visited IDsSet
Removing duplicate items[...new Set(arr)]
Caching user data by user IDMap
Attaching extra data to a DOM elementMap or WeakMap
A lookup that is added to and deleted from oftenMap
What two lists have in common or differ bySet methods

4. How does it work?

TaskMapSet
Createnew Map()new Set()
Addmap.set(key, value)set.add(value)
Readmap.get(key)(the value is the key)
Checkmap.has(key)set.has(value)
Deletemap.delete(key)set.delete(value)
Countmap.sizeset.size
Loopfor (const [k, v] of map)for (const v of set)
Which one to choose
Do you only need unique values?
If yes, use a Set
Do you need key-value with dynamic or non-string keys?
If yes, use a Map
Fixed-shape data that you will send as JSON?
A plain object

Map and Set both iterate in insertion order. But they do not convert directly with JSON.stringify, so you first need Object.fromEntries(map) or [...set].

5. Code example

Set: unique values and set operations

js
const tags = ["js", "react", "js", "css", "react"];
const unique = new Set(tags);

console.log(unique.size);
console.log(unique.has("css"));
console.log([...unique]);

const frontend = new Set(["js", "css", "html"]);
const backend = new Set(["js", "sql"]);

console.log([...frontend.intersection(backend)]);
console.log([...frontend.union(backend)]);
console.log([...frontend.difference(backend)]);

Map: cache and grouping

js
const userCache = new Map();
userCache.set(101, { name: "Ali" });
userCache.set(102, { name: "Sara" });

console.log(userCache.get(101).name);
console.log(userCache.has(103), userCache.size);

const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" },
];
const byStatus = Map.groupBy(orders, (o) => o.status);
console.log(byStatus.get("paid").length);

console.log(Object.fromEntries(userCache));

How does the code work?

PartMeaning
new Set(tags)Duplicates were removed automatically, size is 3
[...unique]Turned the Set back into an array
intersectionWhat both have in common, ["js"]
unionEverything unique, ["js", "css", "html", "sql"]
differenceOnly the frontend ones, ["css", "html"]
userCache.set(101, ...)The number key keeps its type
Map.groupByA Map of groups by status (ES2024)
Object.fromEntriesTurned the Map into a plain object, for JSON

Interview tip

WeakMap and WeakSet can only use objects as keys/values, and they do not prevent garbage collection. They are used to attach private data to DOM elements or objects.

6. Common mistakes

Mistake: Using bracket notation on a Map

Why? map['key'] = value does not create a Map entry, it only adds an object property that get and size do not see.

Better: Always use map.set(key, value) and map.get(key).

Mistake: Expecting a Set to make objects unique by content

Why? Two different objects with the same data are different references, so the Set keeps both.

Better: For objects, use a Set or Map built on a unique key (like id).

Mistake: Calling JSON.stringify directly on a Map

Why? JSON.stringify(map) returns an empty object, and the data is lost.

Better: First use Object.fromEntries(map) or [...map], then stringify.

Mistake: Forcing Map everywhere

Why? Fixed-shape data like a user profile is clearer and more JSON friendly in a plain object.

Better: Use Map for dynamic lookups and an object for a fixed record.

7. What to learn before and after

Suggested order
Objects
Spread & Rest
Map & Set
JSON
Iterators & Generators

Final quick revision

PointDetail
MapA key of any type, get / set / has
SetUnique values only, add / has
Unique array[...new Set(arr)]
OrderBoth keep insertion order
JSONConvert to an object or array first
GroupingMap.groupBy