Chapter 31 of 49

JavaScript Map & Set

So far, we've used objects to store key-value data and arrays to store lists of values. They work well most of the time, but they have a few limitations.

For example, what if you want to:

  • Use an object or a number as a key, not just a string?

  • Keep a list where every value appears only once?

  • Quickly check whether a value exists in a collection of thousands of items?

For these situations, JavaScript gives us two built-in collections: Map and Set.

Map → stores key-value pairs (any type of key)
Set → stores unique values (no duplicates)

Both were added in ES6 (2015) and are used everywhere in modern JavaScript, and in coding interviews too.

Note: when we print a whole Map or Set with console.log(), the output shown in this chapter is what Node.js prints. Browser consoles show the same data in a slightly different style.


What is a Map?

A Map is a collection of key-value pairs where the keys can be of any type, and the pairs are remembered in the order they were inserted.

We create a Map using new Map():

const marks = new Map();

marks.set("Rahul", 85);
marks.set("Priya", 92);
marks.set("Aman", 78);

console.log(marks.get("Priya"));
console.log(marks.size);

Output:

92
3

Notice that we use methods instead of dot or bracket notation:

  • set(key, value) adds or updates a pair.

  • get(key) reads a value.

  • size is a property (not a method) that gives the number of pairs.


Basic Map Methods

Here are the methods you'll use most often:

Method / Property

What it does

map.set(key, value)

Adds or updates a pair and returns the map

map.get(key)

Returns the value, or undefined if the key doesn't exist

map.has(key)

Returns true or false

map.delete(key)

Removes a pair; returns true if something was removed

map.clear()

Removes all pairs

map.size

Number of pairs

Let's see them together:

const stock = new Map();

stock.set("pen", 50).set("notebook", 20).set("eraser", 35);

console.log(stock.has("pen"));
console.log(stock.get("pencil"));

stock.set("pen", 45);   // updates the existing key
console.log(stock.get("pen"));

console.log(stock.delete("eraser"));
console.log(stock.delete("eraser"));
console.log(stock.size);

stock.clear();
console.log(stock.size);

Output:

true
undefined
45
true
false
2
0

Because set() returns the map itself, we can chain several set() calls in one line.

We can also create a Map with initial data by passing an array of [key, value] pairs:

const capitals = new Map([
    ["India", "New Delhi"],
    ["Japan", "Tokyo"],
    ["France", "Paris"]
]);

console.log(capitals);

Output:

Map(3) {
  'India' => 'New Delhi',
  'Japan' => 'Tokyo',
  'France' => 'Paris'
}

Keys Can Be Any Type

This is the biggest difference between a Map and a plain object.

In an object, keys are always converted to strings (or are symbols). So the number 1 and the string "1" become the same key:

const obj = {};

obj[1] = "number one";
obj["1"] = "string one";

console.log(Object.keys(obj));
console.log(obj[1]);

Output:

[ '1' ]
string one

The second assignment overwrote the first. A Map keeps them separate:

const map = new Map();

map.set(1, "number one");
map.set("1", "string one");
map.set(true, "boolean true");

console.log(map.get(1));
console.log(map.get("1"));
console.log(map.size);

Output:

number one
string one
3

Objects as Keys

A Map can even use objects as keys. This is very handy for attaching extra data to an object without modifying it:

const user1 = { name: "Rahul" };
const user2 = { name: "Priya" };

const lastLogin = new Map();

lastLogin.set(user1, "Monday");
lastLogin.set(user2, "Friday");

console.log(lastLogin.get(user1));
console.log(lastLogin.get({ name: "Rahul" }));

Output:

Monday
undefined

Why did the last line give undefined? Because object keys are compared by reference, not by content. { name: "Rahul" } creates a brand new object, which is a different key from user1, even though it looks the same.


Iterating Over a Map

A Map remembers the insertion order of its keys, and it is iterable, so we can loop over it directly with for...of. Each item is a [key, value] array, which we can destructure:

const prices = new Map([
    ["apple", 120],
    ["banana", 40],
    ["mango", 150]
]);

for (const [fruit, price] of prices) {
    console.log(`${fruit}: Rs. ${price}`);
}

Output:

apple: Rs. 120
banana: Rs. 40
mango: Rs. 150

There are also methods to get only the keys, only the values, or the entries:

const prices = new Map([
    ["apple", 120],
    ["banana", 40],
    ["mango", 150]
]);

console.log([...prices.keys()]);
console.log([...prices.values()]);
console.log([...prices.entries()]);

prices.forEach((value, key) => {
    console.log(key, "->", value);
});

Output:

[ 'apple', 'banana', 'mango' ]
[ 120, 40, 150 ]
[ [ 'apple', 120 ], [ 'banana', 40 ], [ 'mango', 150 ] ]
apple -> 120
banana -> 40
mango -> 150

Careful: in map.forEach(), the callback receives (value, key), in that order. The value comes first, just like array.forEach((element, index) => ...).

keys(), values(), and entries() don't return arrays. They return iterators (we'll study these in the next chapter), which is why we used the spread operator [...] to turn them into arrays.


Converting Between Maps and Objects

Since APIs and JSON work with plain objects, we often convert back and forth.

const settings = { theme: "dark", fontSize: 16 };

// Object → Map
const settingsMap = new Map(Object.entries(settings));
console.log(settingsMap.get("theme"));

// Map → Object
settingsMap.set("language", "en");
const backToObject = Object.fromEntries(settingsMap);
console.log(backToObject);

Output:

dark
{ theme: 'dark', fontSize: 16, language: 'en' }

Remember:

Object → Map : new Map(Object.entries(obj))
Map → Object : Object.fromEntries(map)
Map → Array  : [...map]   (array of [key, value] pairs)

A Practical Example: Counting Frequencies

Counting how many times each item appears is one of the most common uses of a Map, both in real projects and in interviews.

function countWords(sentence) {
    const counts = new Map();

    for (const word of sentence.split(" ")) {
        counts.set(word, (counts.get(word) || 0) + 1);
    }

    return counts;
}

const result = countWords("the cat and the dog and the bird");

for (const [word, count] of result) {
    console.log(word, count);
}

Output:

the 3
cat 1
and 2
dog 1
bird 1

The line counts.get(word) || 0 gives 0 the first time we see a word (because get() returns undefined), and the current count after that.

Grouping with Map.groupBy()

Modern JavaScript (ES2024) added Map.groupBy(), which groups the items of an array using a callback:

const students = [
    { name: "Rahul", marks: 82 },
    { name: "Priya", marks: 45 },
    { name: "Aman", marks: 91 },
    { name: "Sneha", marks: 38 }
];

const groups = Map.groupBy(students, s => s.marks >= 50 ? "pass" : "fail");

console.log(groups.get("pass").map(s => s.name));
console.log(groups.get("fail").map(s => s.name));

Output:

[ 'Rahul', 'Aman' ]
[ 'Priya', 'Sneha' ]

It's supported in all modern browsers and Node.js 21+. There is also Object.groupBy(), which returns a plain object instead of a Map.


Map vs Object

Feature

Map

Object

Key types

Any value (objects, numbers, functions...)

Strings and symbols only

Order of keys

Always insertion order

Mostly insertion order, but integer-like keys come first in ascending order

Size

map.size

Object.keys(obj).length

Iteration

Directly iterable with for...of

Needs Object.keys()/entries() or for...in

Accidental keys

None, it starts empty

Inherits from Object.prototype (e.g. "toString" in {} is true)

JSON support

Not directly (JSON.stringify(map) gives "{}")

Yes

Frequent adds/removes

Designed for it

Works, but not optimized for it

A simple rule:

Use an object for a fixed "record" with known property names (like a user profile). Use a Map for a dictionary or lookup table whose keys are added and removed while the program runs.


What is a Set?

A Set is a collection of unique values. A value can appear in a Set only once, no matter how many times you add it.

const tags = new Set();

tags.add("javascript");
tags.add("html");
tags.add("javascript");   // duplicate, ignored
tags.add("css");

console.log(tags);
console.log(tags.size);

Output:

Set(3) { 'javascript', 'html', 'css' }
3

The Set methods are very similar to Map's:

Method / Property

What it does

set.add(value)

Adds a value (if not already present) and returns the set

set.has(value)

Returns true or false

set.delete(value)

Removes a value; returns true if it was removed

set.clear()

Removes everything

set.size

Number of values

A Set has no get() method and no indexes. You don't ask a Set "what is at position 2?". You ask "is this value in the set?".


Removing Duplicates from an Array

The most famous one-liner using a Set:

const numbers = [3, 1, 3, 2, 1, 5, 2];

const unique = [...new Set(numbers)];

console.log(unique);

Output:

[ 3, 1, 2, 5 ]

Here's what happens:

[3, 1, 3, 2, 1, 5, 2]
        ↓  new Set(...)
Set { 3, 1, 2, 5 }        (duplicates dropped, first-seen order kept)
        ↓  [...set]
[3, 1, 2, 5]

You can also use Array.from(new Set(numbers)), which does the same thing.


How a Set Decides "Same Value"

Sets (and Map keys) compare values using an algorithm called SameValueZero. It works almost exactly like ===, with one difference: NaN is considered equal to NaN.

const set = new Set();

set.add(5);
set.add("5");      // different type, so a different value
set.add(NaN);
set.add(NaN);      // NaN counts as the same value
set.add({ id: 1 });
set.add({ id: 1 }); // a different object reference

console.log(set.size);

Output:

5

The two { id: 1 } objects look the same but are separate objects in memory, so the Set keeps both. Sets do not compare objects by their contents.


Iterating Over a Set

Like a Map, a Set keeps insertion order and works with for...of:

const visited = new Set(["Delhi", "Mumbai", "Pune"]);

for (const city of visited) {
    console.log(city);
}

visited.forEach(city => console.log(city.toUpperCase()));

Output:

Delhi
Mumbai
Pune
DELHI
MUMBAI
PUNE

To use array methods like map() or filter(), convert the Set to an array first with [...set].


Set Operations: Union, Intersection, Difference

Since ES2025, Sets have built-in methods for mathematical set operations. They're supported in all modern browsers and in Node.js 22+. Each one returns a new Set and leaves the originals unchanged.

const frontend = new Set(["Rahul", "Priya", "Aman"]);
const backend = new Set(["Priya", "Sneha", "Aman"]);

console.log(frontend.union(backend));
console.log(frontend.intersection(backend));
console.log(frontend.difference(backend));
console.log(frontend.symmetricDifference(backend));

Output:

Set(4) { 'Rahul', 'Priya', 'Aman', 'Sneha' }
Set(2) { 'Priya', 'Aman' }
Set(1) { 'Rahul' }
Set(2) { 'Rahul', 'Sneha' }

Method

Meaning

a.union(b)

Everything in a or b

a.intersection(b)

Only values in both

a.difference(b)

In a but not in b

a.symmetricDifference(b)

In exactly one of them

a.isSubsetOf(b)

true if every value of a is in b

a.isSupersetOf(b)

true if a contains every value of b

a.isDisjointFrom(b)

true if they share no values

If you need to support older environments, the classic way uses filter():

const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);

const common = [...a].filter(x => b.has(x));
const onlyInA = [...a].filter(x => !b.has(x));

console.log(common);
console.log(onlyInA);

Output:

[ 3, 4 ]
[ 1, 2 ]

Set vs Array

Feature

Set

Array

Duplicates

Not allowed

Allowed

Access by index

No

Yes (arr[0])

Check if a value exists

set.has(x), O(1) on average

arr.includes(x), O(n)

Remove a value

set.delete(x), O(1) on average

Find index + splice(), O(n)

Built-in map/filter/sort

No (convert to array first)

Yes

Use a Set when uniqueness or fast membership checks matter. Use an array when order, positions, or duplicates matter.


Time Complexity

JavaScript engines implement Map and Set using hash tables. That makes their main operations very fast:

Operation

Map

Set

Add / update

set() - O(1) average

add() - O(1) average

Look up

get(), has() - O(1) average

has() - O(1) average

Remove

delete() - O(1) average

delete() - O(1) average

Iterate everything

O(n)

O(n)

Space

O(n)

O(n)

This is why replacing array.includes() inside a loop with set.has() can turn an O(n²) solution into an O(n) one.


WeakMap and WeakSet

JavaScript also has WeakMap and WeakSet. They look similar, but with important restrictions:

  • Keys of a WeakMap (and values of a WeakSet) must be objects (or non-registered symbols), not primitives.

  • They hold their keys weakly: if nothing else in the program refers to a key object, it can be garbage collected, and its entry disappears automatically.

  • They are not iterable and have no size, because entries can vanish at any time.

const cache = new WeakMap();

let user = { name: "Rahul" };
cache.set(user, { visits: 3 });

console.log(cache.get(user).visits);

user = null; // the object can now be garbage collected, along with its cache entry

Output:

3

They're mainly used for caching or storing private data about objects without causing memory leaks. As a beginner, you'll use plain Map and Set far more often.


Common Mistakes

1. Using bracket notation on a Map

const map = new Map();

map["name"] = "Rahul";   // ❌ sets a normal property, not a Map entry

console.log(map.get("name"));
console.log(map.size);

Output:

undefined
0

Always use map.set() and map.get().

2. Using length instead of size

const set = new Set([1, 2, 3]);

console.log(set.length);
console.log(set.size);

Output:

undefined
3

3. Expecting JSON.stringify() to work

const map = new Map([["a", 1]]);
const set = new Set([1, 2]);

console.log(JSON.stringify(map));
console.log(JSON.stringify(set));

// Convert first:
console.log(JSON.stringify(Object.fromEntries(map)));
console.log(JSON.stringify([...set]));

Output:

{}
{}
{"a":1}
[1,2]

4. Expecting objects to be compared by content

As we saw, new Set([{ id: 1 }, { id: 1 }]) has size 2. If you need uniqueness by content, use a primitive key, such as user.id, in a Map.


Interview Tips and Practice Problems

Maps and Sets are the JavaScript version of hash maps and hash sets, so they appear in many DSA questions. A classic example is Two Sum: find the indexes of two numbers that add up to a target.

function twoSum(nums, target) {
    const seen = new Map(); // value → index

    for (let i = 0; i < nums.length; i++) {
        const needed = target - nums[i];

        if (seen.has(needed)) {
            return [seen.get(needed), i];
        }

        seen.set(nums[i], i);
    }

    return [];
}

console.log(twoSum([2, 7, 11, 15], 9));
console.log(twoSum([3, 2, 4], 6));

Output:

[ 0, 1 ]
[ 1, 2 ]

This runs in O(n) time and O(n) space, instead of the O(n²) nested-loop approach.

Try these on your own:

  • Contains Duplicate: return true if any value appears twice (hint: compare new Set(arr).size with arr.length).

  • First Non-Repeating Character in a string (hint: count with a Map, then scan again).

  • Valid Anagram: check whether two strings have the same character counts.

  • Intersection of Two Arrays (hint: Set).

  • Longest Substring Without Repeating Characters (hint: sliding window + Set or Map).

Common interview questions on this topic:

  • What is the difference between a Map and an Object?

  • How do you remove duplicates from an array?

  • What is the difference between Map and WeakMap?

  • How does a Set compare NaN and objects?

Conclusion

Map and Set are two powerful built-in collections:

Map → key-value pairs, keys of any type, insertion order kept
Set → unique values only, fast "does it exist?" checks

The core methods to remember:

map.set(key, value);  map.get(key);  map.has(key);  map.delete(key);  map.size;
set.add(value);       set.has(value);               set.delete(value); set.size;

Both are iterable with for...of, both keep insertion order, and both give O(1) average time for adding, finding, and removing items.

In the next chapter, we'll look at iterators and generators, the mechanism that makes Maps, Sets, arrays, and strings work with for...of and the spread operator.