Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Published
2 min read

What Map is

1. The Problem with Traditional Objects

We’ve used Objects as key-value stores forever. But Objects were designed to be records, not high-frequency lookup tables.

  • Key Restrictions: Object keys must be Strings or Symbols. If you try to use a DOM node or another object as a key, it gets stringified to "[object Object]".

  • The Prototype Trap: Objects come with built-in properties like .toString. If you aren't careful, a user input could overwrite a hidden property.

  • Size Matters: Finding the size of an object requires Object.keys(obj).length—an $O(n)$ operation.

2. Enter the Map: A Better Key-Value Store

A Map is a collection of keyed data items, similar to an Object. However, here's the main difference:

  • Any Key Type: You can use a Function, an Object, or even a Boolean as a key.

  • Order is Preserved: Maps remember the insertion order. Objects... well, it’s complicated.

  • Performance: Maps are optimized for frequent additions and removals.

const user1 = { name: "Prakash" };

// Using an object AS a key!
userMetadata.set(user1, { lastLogin: "2026-03-26" });

console.log(userMetadata.get(user1)); // { lastLogin: "2026-03-26" }
console.log(userMetadata.size); // 1 (Instant lookup)

3. The Set: The "No-Duplicates" Engine

An Array is a list; a Set is a collection of unique values.

If you have a list of user IDs and you need to ensure no one is counted twice, an Array requires you to run .includes() or .indexOf()—which gets slower as the list grows ($O(n)$).

A Set handles uniqueness automatically at the engine level.


tags.add("javascript");
tags.add("coding");
tags.add("javascript"); // Duplicate! Ignored automatically.

console.log(tags.size); // 2

Feature

Use Map When...

Use Set When...

Lookup

You need to map "A" to "B" with complex keys.

You just need to know if "A" exists.

Uniqueness

Keys are unique by default.

Every element must be unique.

Performance

Constant searching/deleting of entries.

Removing duplicates from an Array.

Pro Tip: To quickly de-duplicate an array, use the spread operator: const unique = [...new Set(oldArray)];. It’s a clean, one-line "patch" for your data.