:date: Day 76: Set vs Map – When and Why to Use Each in JavaScript

When solving DSA problems or building real-world apps, choosing between a Set and a Map can feel trivial—but it’s not. :crossed_swords: These two data structures serve different purposes, and knowing when to use which can make your code cleaner and faster.

:mag: Map: The Lookup King :crown:
Stores key-value pairs

Keys can be any data type

Keeps insertion order

Access time: O(1)

:brain: Use a Map when:

You need to associate values with keys

You need quick lookups based on a key

You want to track counts, indices, or flags

js
Copy
Edit
const map = new Map();
map.set(‘apple’, 2);
map.get(‘apple’); // 2
:seedling: Set: The Uniqueness Guardian :shield:
Stores only values

Each value must be unique

Also keeps insertion order

Access time: O(1)

:brain: Use a Set when:

You just need to store unique items

You want to check existence fast

You’re cleaning duplicates or tracking seen elements

js
Copy
Edit
const set = new Set([1, 2, 2, 3]);
console.log(set); // Set {1, 2, 3}
:thinking: Real DSA Examples
Use a Set in Longest Substring Without Repeating Characters

Use a Map in Two Sum, Group Anagrams, Top K Frequent Elements

:hammer_and_wrench: Quick Summary:

Use Case Set Map
Unique values only :white_check_mark: Yes :x: No
Key-value pairs :x: No :white_check_mark: Yes
Fast lookup :white_check_mark: Yes :white_check_mark: Yes
Track frequency/index :x: :white_check_mark: Yes

100daysofcode lebanon-mug