WeakMap Methods: set, get, has, delete
You'll learn the four methods available on WeakMap and why it has such a limited API compared to regular Maps.
The Minimal WeakMap Interface
A WeakMap intentionally provides only four methods:
set(key, value)– Adds or updates a key-value pairget(key)– Retrieves the value for a key (returnsundefinedif not found)has(key)– Checks if a key exists (returnstrueorfalse)delete(key)– Removes a key-value pair (returnstrueif deleted,falseif not found)
const wm = new WeakMap();
const obj1 = { id: 1 };
const obj2 = { id: 2 };
// Setting values
wm.set(obj1, 'first object');
wm.set(obj2, 'second object');
// Getting values
console.log(wm.get(obj1)); // "first object"
// Checking existence
console.log(wm.has(obj2)); // true
// Deleting
wm.delete(obj1);
console.log(wm.has(obj1)); // false
Why No Iteration Methods?
Unlike Map, WeakMap has no size, clear(), keys(), values(), entries(), or forEach(). Why? Because WeakMap keys can be garbage collected at any moment without warning. If you could iterate over the keys, you'd get unpredictable results – the list could change mid-iteration as objects are collected. This "weak" nature is the whole point: you can't count entries or enumerate them.
Think of WeakMap like a secret notebook where pages can vanish without notice. You can write notes (set), read specific pages (get), check if a page exists (has), or tear one out (delete), but you can't flip through all pages or count them reliably.
Key Takeaway: WeakMap only offers set, get, has, and delete because its weak references make iteration and size-counting impossible and unpredictable.