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); // 3Methods: 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 collectorUsed for storing private data or caches without interfering with garbage collection.
WeakSet
- Stores only objects, analogous to
WeakMapbut 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 GCComparison
| Feature | Map | Set | WeakMap | WeakSet |
|---|---|---|---|---|
| Storage Type | Key–Value | Unique Values | Key–Value (objects) | Unique Objects |
| Keys | Any type | — | Only objects | Only objects |
| Weak References | ❌ No | ❌ No | ✅ Yes | ✅ Yes |
| Iterability | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
| Removed by GC | ❌ No | ❌ No | ✅ Yes | ✅ Yes |
Key Ideas
MapandSetare general-purpose iterable collections.WeakMapandWeakSetare non-guaranteed collections with weak references that prevent memory leaks.- Use
Mapinstead of plain objects if you need keys of any type. - Use
WeakMap/WeakSetfor temporary, private, or cached data.