# 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

<table style="min-width: 75px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p><strong>Feature</strong></p></td><td colspan="1" rowspan="1"><p><strong>Object</strong></p></td><td colspan="1" rowspan="1"><p><strong>Map</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Key Types</strong></p></td><td colspan="1" rowspan="1"><p>String or Symbol only</p></td><td colspan="1" rowspan="1"><p>Any type (Objects, Funcs, etc.)</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Order</strong></p></td><td colspan="1" rowspan="1"><p>Not reliably ordered</p></td><td colspan="1" rowspan="1"><p>Maintains insertion order</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Size</strong></p></td><td colspan="1" rowspan="1"><p>Manual calculation</p></td><td colspan="1" rowspan="1"><p><code>.size</code> property</p></td></tr><tr><td colspan="1" rowspan="1"><p><strong>Performance</strong></p></td><td colspan="1" rowspan="1"><p>Better for small, static data</p></td><td colspan="1" rowspan="1"><p>Better for frequent adds/removes</p></td></tr></tbody></table>

## 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:

```javascript
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).
