Skip to the content

Lesson 64 of 296

Map and Set

What you will learn

  • What a Map is and how it differs from a plain object
  • Map methods
  • What a Set is
  • Removing duplicates
  • When each one is faster
  • WeakMap and WeakSet
On this page

Map

A Map stores key-value pairs, like an object, but with important differences.

const ages = new Map();
ages.set("Sam", 30);
ages.set("Ali", 25);

ages.get("Sam");       30
ages.has("Ali");       true
ages.size;             2
ages.delete("Ali");
ages.clear();          removes everything

Create from pairs:

const roles = new Map([
  ["sam", "admin"],
  ["ali", "editor"]
]);

Any type can be a key

Object keys are always strings (or symbols). Map keys can be anything: numbers, objects, functions.

const visits = new Map();
const userObj = { id: 1 };
visits.set(userObj, 5);
visits.get(userObj);       5

const obj = {};
obj[1] = "a";
Object.keys(obj);          ["1"]   (the number became a string)

Looping over a Map

A Map remembers insertion order and is directly iterable:

for (const [name, age] of ages) {
  console.log(name, age);
}
ages.forEach((age, name) => console.log(name, age));
[...ages.keys()]           ["Sam", "Ali"]
[...ages.values()]         [30, 25]

Map vs object

Plain objectMap
Key typesStrings and symbolsAny value
OrderMostly insertion order, but integer-like keys come first, sortedAlways insertion order
SizeObject.keys(obj).lengthmap.size
Iterate directly with for...ofNoYes
Inherited keysHas a prototype (keys like toString exist)No inherited keys
Frequent adding and deletingSlowerDesigned for it
Convert to JSONDirectlyNeeds converting first

Use a Map for dynamic collections where keys are added and removed often, or keys are not strings: caches, counts, lookups by ID.
Use an object for fixed-shape records (a user, a config) and data you send as JSON.

Convert between them:

const map = new Map(Object.entries(obj));
const obj2 = Object.fromEntries(map);

Set

A Set stores unique values. Adding a value that is already there does nothing.

const tags = new Set();
tags.add("js");
tags.add("css");
tags.add("js");          ignored
tags.size;               2
tags.has("css");         true
tags.delete("css");

Removing duplicates

const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];       [1, 2, 3]

One of the most useful one-liners in JavaScript. Note: objects are compared by reference, so two different objects with the same contents are both kept.

Speed: why Set and Map are faster for lookups

array.includes(x)      checks every item: slow for big arrays
set.has(x)             one quick check: fast

set.has, map.get and map.has take roughly the same time however big the collection is (described as O(1) in Part 10). array.includes takes longer as the array grows (O(n)).

const blockedIds = new Set(listOfThousandsOfIds);
const visible = posts.filter((p) => !blockedIds.has(p.authorId));

Using a Set here instead of an array can make this many times faster. This "use a Set or Map for fast lookups" idea is the key to many interview problems (Part 10: hashing).

Set operations

Newer JavaScript (ES2025) adds methods for combining sets, available in current browsers and recent Node.js versions:

a.union(b)            everything in either
a.intersection(b)     only in both
a.difference(b)       in a but not b
a.isSubsetOf(b)

In older environments, write them with spread and filter:

const intersection = new Set([...a].filter((x) => b.has(x)));

WeakMap and WeakSet

These are versions that only accept objects as keys, and hold them weakly: if nothing else in the program uses the key object any more, it can be removed from memory, and its entry disappears automatically. They cannot be looped over and have no size.

Use them to attach extra data to objects you do not own (for example DOM elements) without causing memory leaks, or to track visited objects in a deep clone.

Common mistakes

  • Using map["key"] instead of map.get("key").
  • JSON.stringify(map) gives "{}". Convert with Object.fromEntries first.
  • Expecting a Set to remove duplicate objects with the same contents.
  • Using arrays with includes inside loops over large data.

How to say it in an interview

"A Map is a key-value collection where keys can be any type, it keeps insertion order, has a size property, is directly iterable and is optimised for frequent additions and deletions. A Set stores unique values, so spreading a Set is the quickest way to deduplicate an array. Both give near constant-time lookups with has and get, unlike array includes which is linear, so I use them for fast membership checks. WeakMap and WeakSet hold object keys weakly so they do not prevent garbage collection."

Key words

WordMeaning
MapA key-value collection with keys of any type
SetA collection of unique values
DeduplicateRemove duplicates
LookupFinding a value by its key
WeakMap / WeakSetCollections that do not keep their object keys alive
Garbage collectionAutomatic removal of data the program can no longer reach

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.