# Map and Set in JavaScript

If you've been writing JavaScript for a while, you've probably used objects and arrays everywhere. They work — until they don't. That's where `Map` and `Set` come in. They're not new, but a lot of developers skip over them. Let's fix that.

* * *

## What Map is

A `Map` is a collection of key-value pairs — sounds familiar, right? But unlike a plain object, a Map lets you use **anything** as a key. A string, a number, even another object.

```js
const userRoles = new Map();

userRoles.set("alice", "admin");
userRoles.set("bob", "editor");

console.log(userRoles.get("alice")); // "admin"
console.log(userRoles.size);        // 2
```

It keeps things clean and gives you useful built-in methods like `.get()`, `.set()`, `.has()`, and `.delete()`.

* * *

## What Set is

A `Set` is a collection of **unique values**. You can throw duplicates at it — it simply won't store them.

```js
const tags = new Set(["js", "web", "js", "css"]);

console.log(tags); // Set { 'js', 'web', 'css' }
console.log(tags.size); // 3
```

That's it. No duplicates. Ever. It handles that for you automatically.

* * *

## Difference between Map and Object

On the surface, both store key-value pairs. But they behave differently.

|  | Object | Map |
| --- | --- | --- |
| Key types | Only strings/symbols | Anything (objects, numbers, etc.) |
| Order | Not guaranteed (mostly) | Insertion order preserved |
| Size | Manual (`Object.keys().length`) | `.size` property |
| Performance | Slower for frequent add/remove | Optimized for it |

The biggest pain with plain objects is that they come with inherited prototype keys. You might loop over an object and hit properties you never added. Map doesn't have that problem.

```js
// Object issue
const obj = {};
console.log(obj.toString); // function — you didn't add this!

// Map is clean
const map = new Map();
console.log(map.get("toString")); // undefined
```

* * *

## Difference between Set and Array

Both hold lists of values, but they're built for different things.

|  | Array | Set |
| --- | --- | --- |
| Duplicates | Allowed | Not allowed |
| Search (`.includes`) | O(n) — slow on large lists | O(1) — fast |
| Order | Index-based | Insertion order |
| Use case | Ordered list of items | Unique collection of items |

Removing duplicates from an array used to need tricks. With Set, it's one line:

```js
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];

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

* * *

## When to use Map and Set

Here's the honest answer — most of the time, objects and arrays are fine. But reach for Map and Set when:

**Use Map when:**

*   Your keys aren't strings (e.g., using a DOM element or object as a key)
    
*   You need to frequently add/remove entries
    
*   You care about iteration order
    
*   You want to track counts, frequencies, or mappings cleanly
    

**Use Set when:**

*   You need to store unique values and don't want to check manually
    
*   You're doing membership checks often (`.has()` is faster than `.includes()`)
    
*   You want to deduplicate an array quickly
    

```js
// Tracking visited pages — perfect for Set
const visited = new Set();
visited.add("/home");
visited.add("/about");
visited.add("/home"); // ignored

// Counting word frequency — perfect for Map
const freq = new Map();
const words = ["apple", "banana", "apple"];

words.forEach(w => freq.set(w, (freq.get(w) || 0) + 1));
console.log(freq); // Map { 'apple' => 2, 'banana' => 1 }
```

* * *

## Wrapping up

`Map` and `Set` aren't replacements for objects and arrays — they're the right tool for specific jobs. Once you start using them where they fit, your code gets cleaner and often faster too.

Next time you catch yourself writing deduplication logic or wrestling with object keys, remember these two exist.
