Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Updated
6 min read
Map and Set in JavaScript

Intro. First

JavaScript started with just a few basic data structures like Objects and Arrays. For a long time, developers used these two for almost everything—storing collections, managing key-value pairs, tracking uniqueness, and more.

But as applications grew more complex, some limitations of traditional Objects and Arrays became clear. To address these gaps, JavaScript introduced two powerful data structures: Map and Set.

Let’s understand why they exist, what problems they solve, and when you should use them.

The Problem with Traditional Objects and Arrays

Before jumping into Map and Set, it’s important to understand why they were introduced.

Issues with Objects

Objects are commonly used as key-value stores:

const user = {
  name: "Alok",
  age: 21
};

Seems simple—but there are hidden limitations:

  • Keys are always strings or symbols (even if you use numbers, they get converted)

  • No built-in way to know the size easily

  • Not designed for frequent additions/removals

  • Iteration is not as clean or consistent

  • Can accidentally conflict with built-in properties

Example:

const obj = {};
obj[1] = "one";

console.log(obj); // { "1": "one" }

The number 1 becomes a string "1".


Issues with Arrays

Arrays are great for ordered data, but not for uniqueness:

const numbers = [1, 2, 2, 3];
console.log(numbers); // duplicates allowed

Problems:

  • No built-in enforcement of unique values

  • Searching (includes, indexOf) can be inefficient for large datasets

  • Not ideal when you only care about existence, not order

While these issues seems trivial at first but as we proceed with applications of larger scale we soon encounter such issues of development so it's a better choice to simply implement a new data paradigm.


What is a Map?

A Map is a collection of key-value pairs, similar to an object—but more flexible and powerful.

const map = new Map();

map.set("name", "Alok");
map.set(1, "one");
map.set(true, "yes");

console.log(map.get("name")); // Alok

Key Features of Map

  • Keys can be any data type (string, number, boolean, object, function)

  • Maintains insertion order

  • Has a built-in size property

  • Designed for frequent updates and lookups

Example with object as key:

const user = { id: 1 };
const map = new Map();

map.set(user, "User Data");

console.log(map.get(user)); // User Data

This is something regular objects cannot do properly.


What is a Set?

A Set is a collection of unique values.

const set = new Set();

set.add(1);
set.add(2);
set.add(2); // duplicate ignored

console.log(set); // {1, 2}

Key Features of Set

  • Stores only unique values

  • Automatically removes duplicates

  • Maintains insertion order

  • Useful for membership checks

Understanding Uniqueness with Set

One of the most practical uses of Set is removing duplicates:

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

const uniqueNumbers = new Set(numbers);

console.log(uniqueNumbers); // {1, 2, 3, 4}

If needed, you can convert it back to an array:

const result = [...new Set(numbers)];
console.log(result); // [1, 2, 3, 4]

This is much cleaner than manually filtering duplicates. So much time and brainwidth is saved this way. Source: Trust me dude.

Difference Between Map and Object

At first glance, Map and Object seem similar—they both store key-value pairs. But they behave quite differently.

Key Differences

1. Key Types

  • Object: keys must be strings or symbols

  • Map: keys can be any data type

const map = new Map();
map.set(1, "number key");

const obj = {};
obj[1] = "converted to string";

2. Order

  • Object: not strictly guaranteed

  • Map: maintains insertion order

3. Size

  • Object: no direct size property

  • Map: map.size gives total entries

4. Iteration

  • Object: requires methods like Object.keys()

  • Map: directly iterable

for (let [key, value] of map) {
  console.log(key, value);
}

5. Performance

  • Map is optimized for frequent additions/removals

  • Object is better for simple, static structures

Difference Between Set and Array

Both Set and Array store collections of values, but they serve different purposes.

Key Differences

1. Uniqueness

  • Array: allows duplicates

  • Set: automatically removes duplicates

2. Indexing

  • Array: index-based (arr[0])

  • Set: no indexing

3. Methods

  • Array: rich methods (map, filter, reduce)

  • Set: focused on uniqueness (add, has, delete)

4. Use Case

  • Array: ordered lists with possible duplicates

  • Set: unique collections and quick existence checks

When to Use Map and Set

Choosing the right data structure can make your code cleaner and more efficient.

Use Map when:

  • You need a key-value store

  • Keys are not just strings (e.g., objects, numbers)

  • You need frequent updates

  • You care about insertion order

Example:

const cache = new Map();

function storeData(key, value) {
  cache.set(key, value);
}

Use Set when:

  • You need unique values

  • You want to remove duplicates

  • You need fast existence checks

Example:

const visited = new Set();

visited.add("page1");
visited.add("page2");

console.log(visited.has("page1")); // true

Comparing Map with Key-Value Storage

Think of Map as a more advanced version of object-based storage.

Instead of:

const obj = {};
obj["user1"] = "data";

You can use:

const map = new Map();
map.set("user1", "data");

But with Map, you gain:

  • better control over keys

  • predictable iteration

  • cleaner APIs

  • improved performance for dynamic data

Conclusion

Map and Set were introduced to solve real limitations in JavaScript’s traditional data structures.

  • Map improves how we handle key-value data

  • Set ensures uniqueness and simplifies collection management

They are not replacements for Objects and Arrays—but powerful alternatives when used in the right situations.

If you understand when and why to use them, your code becomes:

  1. cleaner

  2. more expressive

  3. more efficient

And that’s exactly what good JavaScript is all about.

I guess it's all about what the task or the application requires in that particular situation.