On this page
Map, Set, WeakMap, and WeakSet
ES6 introduced Map and Set as dedicated collection types, plus WeakMap and WeakSet for memory-sensitive use cases.
Set
A Set stores unique values of any type:
let tags = new Set(['js', 'web', 'js']);
console.log(tags.size); // 2 (duplicates removed)
tags.add('node');
tags.has('web'); // true
tags.delete('web');
tags.clear(); // remove all
// Iterate
for (let tag of tags) {
console.log(tag);
}
Convert array ↔ Set:
let unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
Map
A Map stores key-value pairs where keys can be any type (objects, functions, primitives):
let userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'user');
console.log(userRoles.get('alice')); // 'admin'
console.log(userRoles.size); // 2
// Object as key
let objKey = { id: 1 };
userRoles.set(objKey, 'special');
for (let [key, value] of userRoles) {
console.log(key, value);
}
Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key types | Any | String or Symbol |
| Size | .size |
Manual count |
| Iteration order | Insertion order | Not guaranteed (except integer keys) |
| Default keys | None | Prototype chain |
WeakMap
Keys must be objects. Entries are garbage-collected when the key object is no longer referenced elsewhere:
let cache = new WeakMap();
function process(obj) {
if (cache.has(obj)) return cache.get(obj);
let result = expensiveCompute(obj);
cache.set(obj, result);
return result;
}
No iteration, no .size — designed for private metadata attached to objects.
WeakSet
Stores objects only; weak references allow garbage collection:
let visited = new WeakSet();
function visit(node) {
if (visited.has(node)) return;
visited.add(node);
// process node...
}
Practical Examples
Count occurrences with Map
function countWords(text) {
let counts = new Map();
for (let word of text.toLowerCase().split(/\s+/)) {
counts.set(word, (counts.get(word) || 0) + 1);
}
return counts;
}
Remove duplicates with Set
function uniqueUsers(users) {
return [...new Set(users.map(u => u.id))];
}
Use Set when you need unique values; use Map when you need keyed lookups with non-string keys or guaranteed iteration order.