Skip to main content

Map and Set in JavaScript

Updated 7 min readMarkdown

JavaScript developers used objects and arrays for years to solve almost everything.

Need key-value storage?

Use objects.

Need collections?

Use arrays.

Then JavaScript introduced:

  • Map

  • Set

And suddenly developers realized:

“Wait… we were forcing screwdrivers to behave like hammers this whole time?”

Map and Set were added to solve specific problems more cleanly and efficiently.

If objects and arrays are general-purpose tools, Map and Set are specialized weapons.

Let’s understand them properly before your future codebase becomes a storage warehouse powered by confusion.


What is a Map in JavaScript?

A Map is a collection of key-value pairs.

Sounds similar to objects.

But Map is more flexible and designed specifically for storing data as pairs.

Example:

const user = new Map();

user.set("name", "Gagan");
user.set("age", 19);

console.log(user);

Output:

Map(2) {
  'name' => 'Gagan',
  'age' => 19
}

Understanding Key-Value Storage

A Map stores data like this:

Key        Value
-------------------
name   →   Gagan
age    →   19
city   →   Meerut

Each key maps to a specific value.

That is why it is called:

Map

Common Map Methods

set()

Adds data to the Map.

user.set("country", "India");

get()

Retrieves value using key.

console.log(user.get("name"));

Output:

Gagan

has()

Checks if key exists.

console.log(user.has("age"));

Output:

true

delete()

Removes a key.

user.delete("age");

size

Returns number of entries.

console.log(user.size);

What Makes Map Different from Object?

At first glance, Map and Object seem similar.

But traditional objects have limitations.


Problems with Traditional Objects

1. Object Keys Become Strings

Example:

const obj = {};

obj[1] = "hello";

console.log(obj);

Output:

{ '1': 'hello' }

Even numeric keys become strings.

Objects mainly support:

  • String keys

  • Symbol keys


2. Objects Were Not Designed Purely for Data Storage

Objects also contain:

  • Prototypes

  • Inherited properties

  • Built-in behavior

This can sometimes create unexpected issues.


3. No Easy Size Property

Objects require:

Object.keys(obj).length

Meanwhile Map simply gives:

map.size

Cleaner.

Less mental gymnastics.


Advantages of Map Over Object

1. Any Data Type Can Be a Key

Map keys can be:

  • Strings

  • Numbers

  • Objects

  • Functions

  • Arrays

Example:

const map = new Map();

const objKey = { id: 1 };

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

console.log(map.get(objKey));

Output:

User Data

Objects cannot do this properly.


2. Maintains Insertion Order

Maps preserve the order of entries.

This makes iteration predictable.


3. Better Performance for Frequent Add/Delete Operations

Maps are optimized for dynamic key-value operations.

Especially useful when data changes frequently.


Object vs Map Comparison

Object Map
Keys mainly strings/symbols Keys can be any data type
No direct size property Has size property
Older traditional structure Modern specialized structure
Includes prototype behavior Pure key-value storage
Less optimized for frequent updates Better for dynamic data

What is a Set in JavaScript?

A Set is a collection of unique values.

Keyword:

Unique

Duplicate values are automatically removed.

Example:

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

console.log(numbers);

Output:

Set(4) { 1, 2, 3, 4 }

Notice:

  • Duplicate 2 removed

  • Duplicate 4 removed

Set refuses duplicates like a nightclub bouncer with anger issues.


Why Set Exists

Arrays allow duplicate values.

Example:

const arr = [1, 1, 1, 2, 2, 3];

Sometimes duplicates are unwanted.

Examples:

  • Unique usernames

  • Unique email IDs

  • Unique tags

  • Unique product IDs

Using arrays for uniqueness checking becomes inefficient.

Set solves this cleanly.


Common Set Methods

add()

Adds value to Set.

numbers.add(5);

has()

Checks if value exists.

console.log(numbers.has(2));

delete()

Removes value.

numbers.delete(1);

size

Returns total unique values.

console.log(numbers.size);

Set Uniqueness Visualization

Input Values:
1 → 2 → 2 → 3 → 4 → 4

Stored in Set:
1 → 2 → 3 → 4

Duplicates are ignored automatically.


Difference Between Set and Array

Arrays and Sets both store collections.

But their behavior is different.


Arrays

Arrays:

  • Allow duplicates

  • Support indexing

  • Maintain order

  • Good for ordered collections

Example:

const arr = [10, 20, 20, 30];

Sets

Sets:

  • Store only unique values

  • Do not support indexing directly

  • Maintain insertion order

  • Better for uniqueness handling

Example:

const set = new Set([10, 20, 20, 30]);

Output:

Set(3) {10, 20, 30}

Array vs Set Comparison

Array Set
Allows duplicates Only unique values
Access via index No index access
Good for ordered data Good for uniqueness
More common Specialized collection

Converting Array to Set

One of the most common real-world uses.

Removing duplicates from arrays.

Example:

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

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

console.log(unique);

Output:

[1, 2, 3, 4]

This became one of the most beloved JavaScript tricks because before Set, removing duplicates often involved ugly loops that looked handcrafted during medieval suffering.


Iterating Over Map

Example:

const map = new Map();

map.set("name", "Gagan");
map.set("age", 19);

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

Output:

name Gagan
age 19

Iterating Over Set

Example:

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

for (const value of set) {
  console.log(value);
}

When to Use Map

Use Map when:

  • You need key-value storage

  • Keys are dynamic

  • Keys are not just strings

  • Frequent additions/removals happen

  • You need better organization than plain objects

Examples:

  • Caching systems

  • User session storage

  • Tracking object metadata

  • Dynamic configurations


When to Use Set

Use Set when:

  • You need unique values

  • Duplicate prevention matters

  • Fast existence checking is needed

  • Managing tags/categories

Examples:

  • Unique usernames

  • Tracking online users

  • Removing duplicates

  • Permission systems


Real-World Example of Set

Tracking logged-in users:

const onlineUsers = new Set();

onlineUsers.add("Gagan");
onlineUsers.add("Aditya");
onlineUsers.add("Gagan");

console.log(onlineUsers);

Output:

Set(2) { 'Gagan', 'Aditya' }

Duplicate entries automatically ignored.


Real-World Example of Map

Storing user information:

const users = new Map();

users.set(101, "Gagan");
users.set(102, "Prakhar");

console.log(users.get(101));

Output:

Gagan

Common Beginner Mistakes

1. Treating Set Like Array

Wrong:

set[0]

Sets do not support indexing.


2. Using Object When Map is Better

Some developers force objects into dynamic key-value systems.

Then debugging becomes archaeological excavation.


3. Forgetting Set Removes Duplicates

Some beginners accidentally lose duplicate values without realizing why.

Because Set automatically removes them.


Advantages of Map and Set

Map

  • Flexible keys

  • Better organization

  • Easier iteration

  • Optimized for dynamic operations

Set

  • Automatic uniqueness

  • Fast existence checking

  • Easy duplicate removal


Conclusion

Map and Set are powerful modern JavaScript data structures designed for problems that objects and arrays do not handle efficiently.

Map provides flexible key-value storage.

Set provides collections of unique values.

Understanding when to use them helps developers write:

  • Cleaner code

  • Faster logic

  • Better data structures

  • More maintainable applications

Objects and arrays are still important.

But forcing them into every situation is like using a frying pan to cut wood.

Technically possible. Terrible life choices.

1 view

No comments yet. Be the first to comment.