Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript: Level Up Your Data Structures

Move beyond traditional Arrays and Objects. Learn how Map and Set solve common data-handling problems and make your code infinitely more efficient.

Published
6 min read
H
CS Graduate | Technical Writing | Software development | 20K+ impressions

If you have been coding in JavaScript for any amount of time, you are already intimately familiar with the two heavyweights of data structures: Objects and Arrays.

For 90% of your web development tasks, they are the perfect tools for the job. You use Arrays to hold ordered lists of items, and Objects to hold key-value pairs.

But as you start building larger, more complex applications in Web Dev Cohort 2026, you will start noticing their limitations. Have you ever tried to use an object as a key inside another object? Or have you ever tried to filter out duplicate values from an array without writing complex loops?

To solve these exact problems, ES6 introduced two powerful new data structures: Map and Set.


The Problem with Traditional Objects and Arrays

Before we look at the solutions, let's clearly define the problems.

The limitation of Objects: Objects are strictly designed to use Strings or Symbols as keys. If you try to use a Number, a Boolean, or even another Object as a key, JavaScript will silently convert it into a string "[object Object]". This makes it impossible to link data to complex data types natively.

The limitation of Arrays: Arrays are fantastic for ordered lists, but they have no built-in protection against duplicate values. Furthermore, checking if an item exists inside a massive array (using .includes()) can be slow, because JavaScript has to search through every single item one by one.

Let’s see how Map and Set solve these issues.


What is a Map?

A Map is a collection of keyed data items, just like an Object. However, it removes the biggest restriction of Objects: Map allows keys of ANY type.

You can use a string, a number, a boolean, or even an entire HTML node or JavaScript object as a key.

Creating and Using a Map

To use a Map, we initialize it using the new keyword, and interact with it using built-in methods like .set(), .get(), and .has().

// 1. Create a new Map
const userPreferences = new Map();

// 2. Create some complex keys
const user1 = { name: "Alice" };
const user2 = { name: "Bob" };

// 3. Set values using the objects themselves as keys!
userPreferences.set(user1, "Dark Mode");
userPreferences.set(user2, "Light Mode");
userPreferences.set("default", "System Theme"); // Strings still work too!

// 4. Retrieve the data
console.log(userPreferences.get(user1)); // Output: Dark Mode

// 5. Check the exact size easily
console.log(userPreferences.size); // Output: 3

Map vs. Object: Key Differences

Feature Map Object
Key Types Can be ANY data type (Objects, Functions, Primitives). Must be Strings or Symbols.
Size Property Easily check size using map.size. Requires Object.keys(obj).length.
Order Guarantees insertion order when iterating. Order is not strictly guaranteed.
Iteration Directly iterable (can use for...of loop natively). Requires Object.entries() or Object.keys().

Map Key-Value Storage Visualized

[ TRADITIONAL OBJECT ]
Keys must be Strings ->  { "1": "Apple", "[object Object]": "Banana" }
                             ^                 ^
                     (Number converted)  (Object converted)

[ JAVASCRIPT MAP ]
Keys retain Identity ->  Map {
                           1 => "Apple", 
                           {id: 4} => "Banana", 
                           true => "Cherry"
                         }

What is a Set?

If Map is the upgraded Object, then Set is the specialized Array.

A Set is a collection of values where each value may occur only once. It is entirely focused on uniqueness. If you try to add a value that already exists inside the Set, JavaScript will simply ignore it.

Creating and Using a Set

Just like Map, we use the new keyword to create a Set, and methods like .add(), .has(), and .delete() to interact with it.

const uniqueTags = new Set();

uniqueTags.add("javascript");
uniqueTags.add("react");
uniqueTags.add("javascript"); // Ignored! Already exists.
uniqueTags.add("css");

console.log(uniqueTags); 
// Output: Set(3) { 'javascript', 'react', 'css' }

// Checking for existence is incredibly fast
console.log(uniqueTags.has("react")); // Output: true

Set vs. Array: Key Differences

Feature Set Array
Duplicates Automatically prevents duplicate values. Allows duplicate values.
Data Retrieval Values are not accessed by index (no set[0]). Accessed via index (arr[0]).
Search Speed Extremely fast lookups using set.has(value). Slower lookups using arr.includes(value).

Set Uniqueness Representation

                                     |
                                     V
                           ( Filtered by Set )
                                     |
                                     V
[ OUTPUT SET ]             { "apple", "banana", "mango" }

When to Use Map and Set in the Real World

Knowing how they work is only half the battle. Knowing when to use them is what makes you a senior developer.

Practical Use Cases for Set:

  1. Removing Duplicates from an Array (The Magic Trick): The most common use case for a Set is taking a messy array, throwing it into a Set to filter out duplicates, and spreading it back into a clean array.

    const messyArray =[1, 2, 2, 3, 4, 4, 5];
    const cleanArray =[...new Set(messyArray)]; 
    console.log(cleanArray); // Output:[1, 2, 3, 4, 5]
    
  2. Managing Tags or Categories: If a user is adding tags to a blog post, a Set ensures they can't accidentally add "WebDev" twice.

  3. High-Performance Lookups: If you have a list of 10,000 banned IP addresses and need to check if a user is banned, set.has(ip) is significantly faster than array.includes(ip).

Practical Use Cases for Map:

  1. Caching / Memoization: If you have a function that takes a long time to run on an object, you can use a Map to save the result. Next time you see that exact object, you can instantly return the saved result without recalculating it.

  2. Attaching Data to DOM Elements: In Vanilla JavaScript, if you want to store state or metadata tied to a specific HTML button without polluting the DOM with data- attributes, you can use the DOM node as a Map key!

  3. Frequent Additions/Removals: Maps are optimized for scenarios where key-value pairs are frequently added and removed, making them slightly faster than Objects in highly dynamic environments.

Summary

Objects and Arrays are not going anywhere—they remain the backbone of JavaScript data structures. But when you hit their limitations, Map and Set are your specialized power tools.

  • Use a Map when you need a dictionary/hashmap that requires non-string keys, ordered iterations, or frequent updates.

  • Use a Set when you need a list of absolutely unique items and lightning-fast existence checks.

Add them to your JavaScript code today, and your code will instantly become cleaner and more performant!