new WeakMap().set('name', 'Budi') looks normal, exactly like an ordinary Map. But when you run it, you get a TypeError. A WeakMap has one rule that a Map doesn't have, and there is a reason for that rule.
A WeakMap is like a Map: it stores pairs of a key and a value. There are two differences. Its keys must be objects, and a WeakMap doesn't stop the removal of those objects from memory. A WeakSet is the same, but it stores only objects, with no values. Think of a label stuck on an item: when you throw the item away, the label is gone too. The item is the object, and the label is the data that the WeakMap stores for that object.
Storing data that belongs to an object
This example stores data for the object user, then stops using that object:
const cache = new WeakMap()
let user = { name: 'Budi' }
cache.set(user, 'Budi profile')
console.log(cache.get(user)) // Budi profile
console.log(cache.has(user)) // true
user = null
new WeakMap()makes an empty WeakMap.cache.set(user, 'Budi profile')stores the value'Budi profile'with the objectuseras its key.cache.get(user)gets that value back, with the same object as the key.cache.has(user)answerstrueorfalse, andcache.delete(user)removes the pair.user = nullmakes the variableuserstop pointing at the object made on the second line. Now no code uses the object any more.
JavaScript has a garbage collector: the part that removes from memory the objects nobody uses any more. A WeakMap doesn't count as using the object. So the object that user pointed at may be removed, along with its data in cache. A normal Map is different: the Map keeps holding its keys, so the object and its data stay in memory until you delete them. The browser decides when the removal happens.
Because its content can disappear at any moment, a WeakMap has no size, and you can't loop over it with for...of.
Counting per object
A WeakMap suits extra data per object, for example how many times an object has been used. This example counts visits to a page:
const visits = new WeakMap()
const page = {}
visits.set(page, (visits.get(page) || 0) + 1)
visits.set(page, (visits.get(page) || 0) + 1)
console.log(visits.get(page)) // 2
- The first time,
visits.get(page)is stillundefined, andundefined + 1isNaN. That is why|| 0is there: it uses0as a fallback, a value to use when there is none yet. (... || 0) + 1is the new count, andsetoverwrites the old value with that count.setis called twice, so the result is2.
Keys must be objects
This is the code from the start of the lesson, with a string as the key:
const wm = new WeakMap()
wm.set('name', 'Budi') // TypeError
The result is the TypeError from the start. A string like 'name' can be written again at any time, so it is never truly "removed", and its data would stay forever. That is why a WeakMap refuses a string as a key. Since ES2023, a symbol (a unique value from Symbol()) can be a key too. Need a string or number key? Use a normal Map.
WeakSet: marking objects
This example uses a WeakSet so that one order is not processed twice:
const processed = new WeakSet()
function processOnce(obj) {
if (processed.has(obj)) {
return 'Already processed!'
}
processed.add(obj)
return 'Processing...'
}
const order = { id: 1 }
console.log(processOnce(order)) // Processing...
console.log(processOnce(order)) // Already processed!
The first call marks the object with add. The second call finds it with has, so the answer is different. A WeakSet only has add, has and delete. It answers one question: has this object been marked yet? Like a WeakMap, it holds only objects, and it doesn't stop their removal from memory.
⚠️ Why do I get NaN or undefined?
- Forgetting the fallback.
getfor an object with no data yet givesundefined, andundefined + 1becomesNaN. Add|| 0. - Using a new object as the key.
wm.get({})is alwaysundefined, because a new{}is a different object. Use the same object that you used withset. - Looking for
sizeorfor...of. WeakMap and WeakSet have neither. Need them? Use a Map or a Set.
TL;DR: A WeakMap stores data with objects as keys, through set, get, has and delete. Keys must be objects: a string causes a TypeError. A WeakMap doesn't stop the garbage collector (the part of JavaScript that removes objects no longer in use) from removing that object. So its data is removed too once nothing uses the object. That is why a WeakMap has no size and can't be looped with for...of. A WeakSet stores only objects, for marking them: add, has, delete. For a count per object, use (wm.get(obj) || 0) + 1.
⚡ Keys must be objects
Write:
const wm = new WeakMap()
wm.set('name', 'Budi')
Guess first: does the second line work as it would on an ordinary Map?
No, it causes a TypeError. A WeakMap's keys must be objects. Need a string or number key? Use a normal Map.
Meaning: A WeakMap stores key and value pairs like a Map, with set, get, has and delete. The difference is that only objects can be keys.
⚡ The object is gone, its data is gone too
Write:
const cache = new WeakMap()
let user = { name: 'Budi' }
cache.set(user, 'Budi profile')
user = null
Meaning: After user = null, no code uses the object that was in user any more. The garbage collector is the part of JavaScript that removes from memory the objects nobody uses. A WeakMap doesn't count as using the object, so the garbage collector may remove that object, and its data in cache is removed too. A normal Map keeps its keys, so the object stays. Because its content can disappear at any moment, a WeakMap has no size and can't be looped with for...of.
⚡ A WeakSet for marking
Write:
const processed = new WeakSet()
processed.add(order)
processed.has(order) // true
Meaning: order is an object. A WeakSet stores only objects, with no values, and only has add, has and delete. It answers one question: has this object been marked yet?