Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript: Beyond Objects and Arrays

Published
β€’5 min read
P

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².

JavaScript gives us powerful primitives like objects and arrays, and for a long time they were enough to solve most problems. But as applications grew in complexity, certain limitations became clear. That is where Map and Set come in.

They are not just alternatives. They are purpose-built data structures designed to solve specific problems more cleanly, more predictably, and often more efficiently.

Understanding them properly is a strong signal of maturity as a JavaScript developer.

The Problem with Traditional Objects and Arrays

Before jumping into Map and Set, it is important to understand why they exist.

Problem 1: Objects are not true dictionaries

const user = {};
user["name"] = "Prakash";
user[1] = "one";

console.log(user);

Looks fine, but internally JavaScript converts keys into strings.

console.log(Object.keys(user)); 
// ["1", "name"]

Even if you use numbers or objects as keys, they get coerced into strings. This creates limitations when you need precise key control.

Problem 2: Arrays allow duplicates

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

There is no built-in guarantee of uniqueness. You must manually filter duplicates.

These problems led to the introduction of Map and Set.

What is a Map?

A Map is a collection of key-value pairs where keys can be of any type.

Unlike objects, keys are not restricted to strings or symbols.

Syntax

const map = new Map();

Example

const userMap = new Map();

userMap.set("name", "Prakash");
userMap.set(1, "one");

console.log(userMap.get("name")); // Prakash
console.log(userMap.get(1));      // one

Key Characteristics of Map

1. Keys can be anything

const objKey = { id: 1 };

const map = new Map();
map.set(objKey, "data");

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

This is impossible with normal objects.

2. Maintains insertion order

const map = new Map();
map.set("a", 1);
map.set("b", 2);

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

Output will always follow insertion order.

3. Built-in methods for better control

map.has("a");   // true
map.delete("a");
map.size;       // number of elements
map.clear();

Conceptual Visualization of Map

Think of Map like a structured table:

Key β†’ Value "name" β†’ "Prakash" 1 β†’ "one" { id: 1 } β†’ "data"

Each key directly maps to a value without type restrictions.

What is a Set?

A Set is a collection of unique values.

It automatically removes duplicates and ensures that each value appears only once.

Syntax

const set = new Set();

Example

const numbers = new Set();

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

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

Key Characteristics of Set

1. Only unique values

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

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

2. No indexing

Unlike arrays, you cannot access elements by index.

set[0]; // undefined

3. Useful methods

set.has(1);    // true
set.delete(1);
set.size;      
set.clear();

Conceptual Visualization of Set

Think of Set as a filter that removes duplicates automatically:

Input: [1, 2, 2, 3, 3] Output: {1, 2, 3}

No duplicates survive.

Map vs Object

Feature Map Object
Key types Any type String or Symbol
Order Maintains insertion order Not strictly guaranteed
Performance Optimized for frequent add/remove Not optimized for that
Size map.size Object.keys(obj).length
Iteration Directly iterable Requires methods

Example Comparison

const obj = {};
obj[{}] = "value";

console.log(obj); 
// key becomes "[object Object]"
const map = new Map();
const key = {};

map.set(key, "value");
console.log(map.get(key)); // correct

Map preserves key identity. Object does not.

Set vs Array

Feature Set Array
Duplicates Not allowed Allowed
Order Maintained Maintained
Indexing No Yes
Performance (search) Faster (has) Slower (includes)

Example Comparison

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

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

Set is often used to remove duplicates from arrays.

When to Use Map

Use Map when:

You need key-value storage with flexible key types You need reliable insertion order You frequently add and remove entries You want better performance for lookups

Example Use Case

const cache = new Map();

function getData(key) {
  if (cache.has(key)) {
    return cache.get(key);
  }

  const result = "expensive computation";
  cache.set(key, result);
  return result;
}

When to Use Set

Use Set when:

You need unique values You want to remove duplicates You want fast existence checks

Example Use Case

const visited = new Set();

function visit(page) {
  if (visited.has(page)) {
    console.log("Already visited");
    return;
  }

  visited.add(page);
  console.log("Visiting:", page);
}

Deep Insight

Map and Set are not just new syntax. They represent a shift in thinking.

Objects were designed for structure. Arrays were designed for ordered lists.

But modern applications need:

Precise control over keys Guaranteed uniqueness Efficient lookups

Map and Set solve these problems directly.


❊ Want More…?

I write articles on blog.prakashtsx.com and also post development-related content on the following platforms:

JavaScript

Part 1 of 15

In this series of blogs I have written some interesting concepts related to JavaScript.

Up next

The Magic of this, call(), apply(), and bind() in JavaScript

Understanding call(), apply(), and bind() in JavaScript

More from this blog

Learn with Prakash

40 posts

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².