Dmytro Morar
JavaScript

Map Set WeakMap WeakSet

Map, Set, WeakMap, and WeakSet collections are built-in data structures in JavaScript designed for storing unique values and key–value pairs. They resolve the limitations of plain objects and arrays.

Map

  • Stores data as key–value pairs.
  • Keys can be of any type (including objects and functions).
  • Preserves element insertion order.
const map = new Map();
map.set('name', 'Alex');
map.set({ id: 1 }, 'Object key');
console.log(map.get('name')); // 'Alex'

Methods: set(), get(), has(), delete(), clear(), size. Iterates via for...of, map.entries(), map.keys(), map.values().

Set

  • Stores unique values of any type.
  • When adding a value again — ignores duplicates.
  • Preserves insertion order.
const set = new Set([1, 2, 2, 3]);
console.log(set.size); // 3

Methods: add(), has(), delete(), clear(). Often used to remove duplicates from an array:

const unique = [...new Set(array)];

WeakMap

  • Keys can only be objects.
  • Stores weak references — if an object becomes unreachable, the entry is automatically removed by the GC.
  • Not iterable (cannot get a list of keys or values).
let obj = {};
const weakMap = new WeakMap();
weakMap.set(obj, 'data');
obj = null; // entry will be removed by the garbage collector

Used for storing private data or caches without interfering with garbage collection.

WeakSet

  • Stores only objects, analogous to WeakMap but without key–value pairs.
  • Not iterable, does not have size.
  • An element is removed if there are no other references to it.
let user = { name: 'John' };
const weakSet = new WeakSet();
weakSet.add(user);
user = null; // will be removed by GC

Comparison

FeatureMapSetWeakMapWeakSet
Storage TypeKey–ValueUnique ValuesKey–Value (objects)Unique Objects
KeysAny typeOnly objectsOnly objects
Weak References❌ No❌ No✅ Yes✅ Yes
Iterability✅ Yes✅ Yes❌ No❌ No
Removed by GC❌ No❌ No✅ Yes✅ Yes

Key Ideas

  • Map and Set are general-purpose iterable collections.
  • WeakMap and WeakSet are non-guaranteed collections with weak references that prevent memory leaks.
  • Use Map instead of plain objects if you need keys of any type.
  • Use WeakMap / WeakSet for temporary, private, or cached data.

On this page