Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Understanding Modern Data Structures Beyond Objects and Arrays

Updated
•3 min read•View as Markdown

Introduction

When we begin working with JavaScript, you typically reply on objects and arrays to manage data. They are useful and flexible, but as your application become more complex, their drawbacks can become noticeable.

This is where Map and Set step in. These newer data structures are built to handle certain tasks more efficiently and provide cleaner solutions for specific use cases.


What is a Map?

A Map is a collection of key-value pairs, just like an object - but more flexible and predictable.

Basic Example

const userMap = new Map();

userMap.set("name", "Elon");
userMap.set("age", 30);

console.log(userMap.get("name")); // Elon

Key Points

  • Keys can be any type (not just strings)

  • Maintains insertion order

  • Has built-in methods like .set(), .get(), .has(), .delete()

Using Objects as Keys

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

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

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

This is something objects cannot do reliably.


What is a Set?

A Set is a collection of unique values.

Basic Example

const numbers = new Set();

numbers.add(1);
numbers.add(2);
numbers.add(2);

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

Key Points

  • Stores only unique values

  • Automatically removes duplicates

  • Has methods like .add(), .delete(), .has()


Problem with Traditional Objects

Objects are great, but they have some limitations,

const obj = {};

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

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

Issues

  • Keys are converted to strings

  • No guaranteed order (historically)

  • Not ideal for frequent additions/removals

This makes objects less reliable for dynamic key-value storage.


Map vs Object

Feature Map Object
Key Types Any type Strings & Symbols only
Order Maintains insertion order Not strictly guaranteed
Performance Optimized for frequent ops Not optimized for this
Size .size property Manual counting needed

Problem with Arrays (Duplicates)

Arrays allow duplicates by default:

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

If you want unique values, you need extra logic.


Set vs Array

Feature Set Array
Duplicates Not allowed Allowed
Order Maintained Maintained
Methods .add(), .has() .push(), .includes()
Use Case Unique values Ordered collections

Removing Duplicates with Set

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

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

console.log(unique); // [1, 2, 3]

When to Use Map

Use Map when:

  • You need key-value pairs

  • Keys are not just strings

  • You need frequent insert/delete operations

  • You care about insertion order


When to Use Set

Use Set when:

  • You need unique values only

  • You want to remove duplicates

  • You need fast existence checks


1 views