Explain Set vs Map vs plain Object in JS

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

FeatureSetMapObject
StoresValues onlyKey–Value pairsKey–Value pairs
Keys typeN/AAny typeString or Symbol only
Keeps orderMostly ✅ (strings only)
Duplicates❌ (keys)❌ (keys)
Iterationfor...of, .forEach()for...of, .forEach()for...in, Object.keys()
Key lookup.has(value).has(key)key in obj or obj.key
Best forUnique valuesArbitrary key–value mappingSimple key–value mapping

Leave a Reply

Your email address will not be published. Required fields are marked *