What is difference between WeakMap() and Map()

Saurav sharma
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?

  1. 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.
  2. When you set obj = null, the original object is no longer referenced anywhere in the code.
  3. Since WeakMap only holds objects as keys, and the object has been garbage collected, the key is automatically removed from the WeakMap.

Why is the second console output undefined?

  1. Although Map holds a strong reference to its keys, you assigned null to obj, which means obj no longer refers to the original object.
  2. The key (the original object) still exists in the Map, but you're calling strongMap.get(null), which does not exist in the Map.
  3. Since null was never a key in strongMap, strongMap.get(null) returns undefined.

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), whereas WeakMap only supports objects.

I hope this article helps you understand the difference between Map and WeakMap!

--

--

Saurav sharma
Saurav sharma

No responses yet