What is difference between WeakMap() and Map()
1 min readFeb 12, 2025
Can you guess the output?
Both console.log
statements return undefined
, but for different reasons.
Why is the first console output undefined
?
WeakMap
holds a weak reference to its key-value pairs, meaning the keys can be garbage collected when there are no other references to them.- When you set
obj = null
, the original object is no longer referenced anywhere in the code. - Since
WeakMap
only holds objects as keys, and the object has been garbage collected, the key is automatically removed from theWeakMap
.
Why is the second console output undefined
?
- Although
Map
holds a strong reference to its keys, you assignednull
toobj
, which meansobj
no longer refers to the original object. - The key (the original object) still exists in the
Map
, but you're callingstrongMap.get(null)
, which does not exist in theMap
. - Since
null
was never a key instrongMap
,strongMap.get(null)
returnsundefined
.
Key Takeaways
WeakMap
entries automatically disappear when the key is garbage collected.Map
retains its keys unless explicitly deleted.Map
supports any data type as keys (strings, numbers, objects), whereasWeakMap
only supports objects.
I hope this article helps you understand the difference between Map
and WeakMap
!