tryjs.app

JavaScript Map & Set — Runnable Examples

Learn JavaScript Map and Set with runnable examples. Key-value pairs with any key type, guaranteed unique values, and set operations like intersection and union.

Map & Set

Built-in collection types

javascriptJS Fundamentals
// Map: key-value pairs (any key type)
const map = new Map();
map.set("name", "Alice");
map.set(42, "the answer");
map.set(true, "yes");

for (const [key, value] of map) {
  console.log(`${key} => ${value}`);
}
console.log("size:", map.size);

// Set: unique values
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)];
console.log("Unique:", unique);

// Set operations
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
const intersection = [...a].filter(x => b.has(x));
const union = new Set([...a, ...b]);
console.log("Intersection:", intersection);
console.log("Union:", [...union]);

Overview

Map and Set are collection types added in ES2015 that fix long-standing gaps in plain objects and arrays. Map is a key-value store that accepts any value as a key (not just strings), preserves insertion order, and exposes size directly. Set stores unique values and gives you deduplication and fast has()-checks for free. Both are iterable and both have small but crucial performance characteristics that objects and arrays don't.

How It Works

Map: any-key key-value store

new Map() creates an empty map. set(key, value) stores, get(key) retrieves, has(key) checks, delete(key) removes, size returns the entry count. Keys can be objects, functions, booleans, or NaN — anything.

Set: unique values

new Set(iterable) creates a set from any iterable and drops duplicates. add(value) inserts, has(value) checks in O(1), delete(value) removes. Iteration order is insertion order.

Map preserves insertion order, Object doesn't guarantee it

Objects technically maintain insertion order for string keys in modern engines, but integer-like keys are sorted numerically. Map always iterates in strict insertion order, no exceptions.

Set operations via spread

Intersection, union, and difference aren't built in but are one-liners with spread: [...a].filter(x => b.has(x)) is intersection, new Set([...a, ...b]) is union.

Common Mistakes

  • Using an object as a map when keys aren't strings — you'll silently convert everything to strings via toString().
  • Forgetting that Map has .size and Object doesn't — you need Object.keys(obj).length for plain objects.
  • Using Set with objects and expecting value-equality — Set compares by reference, so two equal objects are still distinct.
  • JSON.stringify ignores Map and Set — they serialize to {} and {}. Convert to array first if you need to serialize.

When to Use It

Use Map whenever your keys aren't strings, when you need size or insertion order, or when you're frequently adding and removing keys (Map is faster than Object for that workload). Use Set whenever you need deduplication or fast membership checks on a collection of values.

Frequently Asked Questions

What is the difference between Map and Object in JavaScript?

Map accepts any value as a key (not just strings), preserves insertion order, and exposes .size directly. Object keys are always coerced to strings (or symbols), and there's no .size property. Map is also faster for frequent additions and deletions.

When should I use Set instead of an array?

Use Set when you need uniqueness or fast has() lookups. Checking membership with array.includes is O(n); Set.has is O(1). Deduplicating an array is a one-liner: [...new Set(arr)].

Can I JSON.stringify a Map or Set?

Not directly — both serialize to {} or {}. Convert them first: JSON.stringify([...map]) for Map, JSON.stringify([...set]) for Set.

How do I do set intersection or union in JavaScript?

Intersection: [...a].filter(x => b.has(x)). Union: new Set([...a, ...b]). Difference: [...a].filter(x => !b.has(x)). Modern browsers are adding Set.prototype.intersection/union/difference — check support before using.