Alright — here’s a clear breakdown of how Set, Map, and plain Object differ in JavaScript.
1. Set
- Purpose: Stores unique values only (no duplicates).
- Keys/Values: Only values — no key–value pairs.
- Order: Preserves insertion order.
- Duplicates: Automatically removed.
- Access: Check if a value exists with
.has(value). - Iterables: Yes, can loop directly with
for...of.
Example:
const set = new Set([1, 2, 2, 3]);
console.log(set); // Set(3) {1, 2, 3}
set.add(4);
set.has(2); // true
set.delete(1);
When to use:
- Removing duplicates from arrays
- Tracking unique visited items in algorithms
- Representing a “membership” list
2. Map
- Purpose: Stores key–value pairs.
- Keys: Can be any type (objects, arrays, functions, primitives).
- Order: Preserves insertion order.
- Duplicates: Key uniqueness is enforced.
- Access:
.get(key)and.set(key, value).
Example:
const map = new Map();
map.set("name", "Varun");
map.set({ id: 1 }, "Custom Object Key");
map.set(42, "Number Key");
console.log(map.get("name")); // Varun
When to use:
- When you need keys that are not just strings (like objects or functions)
- When you care about insertion order and quick lookups
- Storing metadata for objects
3. Object
- Purpose: Also stores key–value pairs, but keys are always strings or symbols.
- Order: Generally insertion order for strings (but not guaranteed historically).
- Duplicates: Key overwrites if added again.
- Access: Dot notation (
obj.key) or bracket notation (obj["key"]).
Example:
const obj = {};
obj.name = "Varun";
obj[42] = "Number key as string";
console.log(obj["42"]); // Number keys become strings: "Number key as string"
When to use:
- For structured data modeling (like JSON)
- When you don’t need arbitrary object/array/function keys
- When you want prototypes and methods
Quick Comparison Table
| Feature | Set | Map | Object |
|---|---|---|---|
| Stores | Values only | Key–Value pairs | Key–Value pairs |
| Keys type | N/A | Any type | String or Symbol only |
| Keeps order | ✅ | ✅ | Mostly ✅ (strings only) |
| Duplicates | ❌ | ❌ (keys) | ❌ (keys) |
| Iteration | for...of, .forEach() | for...of, .forEach() | for...in, Object.keys() |
| Key lookup | .has(value) | .has(key) | key in obj or obj.key |
| Best for | Unique values | Arbitrary key–value mapping | Simple key–value mapping |