Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript: Modern Tools for Better Data Management

Updated
4 min read
Map and Set in JavaScript: Modern Tools for Better Data Management
A

Focused on building robust web applications and understanding the underlying infrastructure of the internet.

For years, JavaScript developers relied almost exclusively on Objects and Arrays to handle data. While they are powerful, they have limitations that become obvious as your application grows. Objects can be picky about their keys, and Arrays can become slow and messy when you need to ensure every item is unique.

To solve these problems, ES6 introduced two specialized data structures: Map and Set. Think of these as the "Pro" versions of objects and arrays—optimized for specific tasks, more predictable, and packed with useful features.

1. The Map: The Supercharged Dictionary

A Map is a collection of keyed data items, similar to an Object. However, the major difference lies in the Keys. In a standard object, keys must be strings or symbols. In a Map, keys can be anything—numbers, booleans, or even other objects and functions.

Creating and Using a Map

const userRoles = new Map();

// Adding data
userRoles.set("Abhishek", "Admin");
userRoles.set(101, "Editor");
const guestObj = { id: 1 };
userRoles.set(guestObj, "Viewer"); // Using an object as a key!

// Accessing data
console.log(userRoles.get("Abhishek")); // "Admin"
console.log(userRoles.size); // 3

2. Map vs. Object: Which One is Better?

If you just need a simple place to store a few settings, an Object is fine. But for dynamic data, a Map often wins.

Feature Object Map
Key Types Strings or Symbols only. Anything (Objects, Numbers, etc.).
Ordering No guaranteed order for strings. Preserves insertion order.
Size Must be calculated manually. Has a built-in .size property.
Performance Better for small, static data. Optimized for frequent additions/removals.
Iteration Requires Object.keys() etc. Directly iterable with for...of.

3. The Set: The Ultimate Filter

A Set is a collection of values where each value can occur only once. It’s like a VIP guest list: if someone is already on the list, you can't add them again. This makes Sets incredibly useful for removing duplicates and checking for existence.

Creating and Using a Set

const guests = new Set();

guests.add("Alice");
guests.add("Bob");
guests.add("Alice"); // This is ignored because "Alice" already exists

console.log(guests.size); // 2
console.log(guests.has("Bob")); // true

4. Set vs. Array: The Performance Edge

While you can use an array to store unique values by manually checking if (arr.includes(val)), it’s much slower.

Feature Array Set
Duplicates Allowed. Automatically prevented.
Order Indexed by number (0, 1, 2). Preserves insertion order (no index).
Speed Checking existence (includes) is slow ($O(n)$). Checking existence (has) is fast ($O(1)$).
Access Access elements via arr[index]. Must iterate or convert to access values.

5. When to Reach for Map and Set?

Use a Map when:

  • You need keys that aren't strings (e.g., mapping a DOM element to some data).

  • The order of the data matters.

  • You are constantly adding and removing keys and need high performance.

  • You need to quickly find out how many items are in the collection.

Use a Set when:

  • You want to find the unique values from an array.

  • You need to keep track of a list of items where duplicates make no sense (like tags on a blog post).

  • You frequently check if an item exists in a list (like checking if a user ID is in a "blocked" list).

The Famous One-Liner: The most common use of Set is to remove duplicates from an array in a single line of code:

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)]; // [1, 2, 3, 4, 5]

Summary

  • Map: A better dictionary. Supports any key type, stays ordered, and knows its own size.

  • Set: A collection of unique items. Perfect for lists that shouldn't have duplicates.

  • Method Recap:

    • Map: .set(), .get(), .has(), .delete(), .clear()

    • Set: .add(), .has(), .delete(), .clear()

  • Iteration: Both are iterable, making them work perfectly with modern for...of loops and the Spread operator.

More from this blog

T

Terminal Thoughts

53 posts

A developer’s log of experiments, errors, and breakthroughs. Terminal and Thoughts captures my evolution through a web development cohort, featuring deep dives into the modern tools and technologies.