Skip to main content

Command Palette

Search for a command to run...

Map and Set in Javascript

Updated
•6 min read•View as Markdown
Map and Set in Javascript

Introduction

In this article/blog we are going to discuss about the Map and Set in javascript, which were not the part of javascript before ES6. For a long time, the JavaScript world was a bit of a duopoly. If you had a list of things, you used an Array. If you had a collection of key-value pairs, you used an Object.

But as applications grew more complex, the limitations of these "OG" data structures started to show. Enter ES6 with Map and Set—the specialized tools you didn't know you needed, but won't be able to live without once you use them.

The Problem with the "Old Guard"

Before we dive into the new stuff, let’s be real about the traditional tools:

  • Objects were never actually meant to be general-purpose maps. They were designed to hold properties for an instance. This leads to issues like prototype pollution (where your object "inherits" keys you didn't define) and the annoying fact that keys must be strings or symbols.

  • Arrays are great for ordered lists, but checking if an item exists in a massive array is like looking for a specific sock in a laundry basket—you have to look at every single piece until you find it.


Map : (key : value)

Map is a collection of key value data items similar to an object but with some extra superpowers, how map is built for high - performance key-value storage.

Creating a Map

const map = new Map();

Core Methods

Method Description
map.set(key, value) Add or update a key-value pair
map.get(key) Get value by key
map.has(key) Check if key exists → true/false
map.delete(key) Remove a key-value pair
map.clear() Remove all entries
map.size Number of entries

Basic Example

const map = new Map();

map.set("name", "Alice");
map.set(42, "answer");
map.set(true, "yes");

map.get("name");  // "Alice"
map.get(42);      // "answer"
map.has(true);    // true
map.size;         // 3

Any Type as Key

const obj = { id: 1 };
const fn  = () => {};

const map = new Map();
map.set(obj, "an object key");
map.set(fn,  "a function key");

map.get(obj); // "an object key"
map.get(fn);  // "a function key"

⚠️ A plain object would convert these keys to the string "[object Object]", losing data. Map preserves the actual reference.

Initializing with Data

const map = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
]);

Iterating a Map

Maps maintain insertion order, which makes iteration predictable.

const map = new Map([["x", 10], ["y", 20], ["z", 30]]);

// Keys
for (const key of map.keys())   console.log(key);   // x y z

// Values
for (const val of map.values()) console.log(val);   // 10 20 30

// Entries
for (const [key, val] of map)   console.log(key, val); // x 10 ...

// forEach
map.forEach((value, key) => console.log(key, value));

Why Map is better than Object for data storage:

  • Any Key Type: Want to use a function as a key? Or another object? Or the number 42? A Map says, "Sure, why not?" Objects, meanwhile, will quietly convert your keys into strings.

  • Size for Free: To get the size of an Object, you usually have to do Object.keys(obj).length. With a Map, you just check .size.

  • Order Matters: Maps remember the original insertion order of the keys. Objects... well, it’s complicated.

  • Performance: Maps are optimized for frequent additions and removals of key-value pairs.

Map vs. Object: At a Glance

Feature Map Object
Key types Any type String / Symbol only
Insertion order ✅ Always preserved ✅ (mostly, for strings)
Size map.size Object.keys(obj).length
Iteration Easy, built-in Requires Object.keys() etc.
Performance Better for frequent add/delete Fine for static data
JSON support ❌ Not directly ✅ JSON.stringify works

Set - Uniqueness

A set is a collection of values where each value can be appear only once, it is a collection of unique values where duplicate values are automatically removed. So removing the duplicate the value is the superpower of the set.

Creating a Set

const set = new Set()

Core Methods

Method Description
set.add(value) Add a value
set.has(value) Check if value exists → true/false
set.delete(value) Remove a value
set.clear() Remove all values
set.size Number of unique values

Basic Example

const set = new Set();

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

set.has(2);   // true
set.has(99);  // false
set.size;     // 3  (not 4)

Initializing with Data

const set = new Set([1, 2, 3, 2, 1]);
// Set { 1, 2, 3 }  — duplicates removed automatically

Most Common Use Case — Remove Duplicates from Array

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

Set vs. Array: Why bother?

  • Automatic Uniqueness: No more writing .includes() checks before pushing to an array.

  • Speed: Checking if an element exists in a Set using .has(value) is significantly faster than using Array.includes(value), especially as the data grows.

Set vs Array — When to Use Which

Feature Set Array
Unique values ✅ Automatic ❌ Manual check needed
Index access ❌ No set[0] ✅ arr[0]
Lookup speed ✅ O(1) with has() ❌ O(n) with includes()
Duplicates ❌ Not allowed ✅ Allowed
Order ✅ Insertion order ✅ Insertion order

When to use which

Use a Map when:

  • You need keys that aren't strings.

  • You need to maintain the order of elements.

  • You are constantly adding and removing pairs (performance).

  • You need to store metadata about an object without modifying the object itself.

Use a Set when:

  • You need to store a list of unique items.

  • You need to perform high-speed "existence checks" (is this user ID in the list?).

  • You want to easily remove duplicates from an existing collection.


The Verdict

Objects and Arrays aren't going anywhere—they are still the backbone of JavaScript. However, using a Map or Set isn't just about being "fancy"; it's about using the right tool for the job.

Next time you find yourself manually checking for duplicates or struggling with object keys, remember: there’s a better way. Give Map and Set a seat at your table.

Do you find yourself using Map and Set in your daily workflow, or are you still sticking to the classic Object and Array duo?