Hiprup

What are Set and Map in JavaScript?

Set and Map are modern collection types that improve on plain arrays and objects.

  • Set — a collection of unique values; great for removing duplicates and fast membership checks.

  • Map — key–value pairs where keys can be any type (not just strings) and insertion order is preserved.

  • Both — have a size property and are easily iterable.

When to use: Map over a plain object when keys aren't strings or order matters; Set to enforce uniqueness.

// Set — unique values
const set = new Set([1, 2, 3, 2, 1]);
console.log(set);         // Set(3) {1, 2, 3} — duplicates removed
set.add(4);               // Set(4) {1, 2, 3, 4}
set.has(2);               // true (O(1))
set.delete(2);            // true
set.size;                 // 3

// Deduplicate an array
const unique = [...new Set([1, 2, 2, 3, 3, 3])]; // [1, 2, 3]

// Map — any-type keys
const map = new Map();
const objKey = { id: 1 };
map.set(objKey, 'User 1');   // Object as key!
map.set('name', 'John');
map.set(42, 'the answer');

console.log(map.get(objKey)); // 'User 1'
console.log(map.size);        // 3

// Map from entries
const userMap = new Map([
  ['alice', { age: 25 }],
  ['bob', { age: 30 }]
]);

// Iteration
for (const [key, value] of userMap) {
  console.log(`${key}: ${value.age}`);
}

// Set operations
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const union = new Set([...a, ...b]);           // {1, 2, 3, 4}
const intersection = new Set([...a].filter(x => b.has(x))); // {2, 3}
const difference = new Set([...a].filter(x => !b.has(x)));  // {1}

Set automatically removes duplicates. [...new Set(array)] is the cleanest deduplication. Map supports any key type — objKey is an object used as a key (impossible with plain objects). Map.get/set/has are all O(1).

Set operations use spread + filter. Both are iterable with for...of.

Set for deduplication ([...new Set(arr)]) is the #1 practical use. Map for object keys is the key advantage over plain objects.

Know O(1) operations for both. Set operations (union, intersection, difference) show deeper knowledge.