Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Published
2 min read
Map and Set in JavaScript

What is a Map?

A Map is a collection of keyed data items, similar to an Object. However, the primary difference is that Map allows keys of any type functions, objects, or even primitives.

Map vs Object

Feature

Object

Map

Key Types

String or Symbol only

Any type (Objects, Funcs, etc.)

Order

Not reliably ordered

Maintains insertion order

Size

Manual calculation

.size property

Performance

Better for small, static data

Better for frequent adds/removes

What is a Set?

A Set is a collection of values where each value must be unique. Think of it as an Array with a built-in "no duplicates" policy.

The Power of Uniqueness

The most common use case for a Set is instantly cleaning an array. If you have a list of user IDs with duplicates, you can wipe them out in one line:

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

Set vs. Array

  • Search Speed: Checking if an item exists in an Array (arr.includes(x)) takes O(n) time. In a Set (set.has(x)), it is O(1). If you have 10,000 items, the Set is orders of magnitude faster.

  • No Duplicates: Arrays allow you to push the same value a million times. Sets silently ignore duplicates, keeping your data clean automatically.

When to reach for Map and Set

Use a Map when:

  • You need keys that aren't strings (e.g., associating metadata with a DOM element).

  • You need to frequently add and remove key-value pairs (Maps are optimized for this).

  • You need to iterate over data in the exact order it was added.

Use a Set when:

  • You are dealing with a list where duplicates are logically impossible or unwanted (like a list of "Liked" posts).

  • You need to perform high-speed "existence checks" (checking if a username is already taken in a local list).

JavaScript

Part 6 of 24

Master JavaScript from the ground up with a structured, easy-to-follow learning path designed for serious developers. This series starts with core fundamentals like variables, data types, and control flow, then gradually moves into deeper topics such as functions, scope, prototypes, asynchronous programming, and how the JavaScript engine works internally. Each lesson focuses on clarity and real understanding. You will learn not only how to write JavaScript, but why it behaves the way it does. Concepts are explained using simple examples, practical use cases, and clean coding patterns that reflect real-world development.

Up next

Spread vs Rest Operators in JavaScript

Let's go through spread and rest operators