JavaScript WeakMap

Subject: JavaScript

A WeakMap is a built-in object in JavaScript that stores key-value pairs, where keys must be objects and values can be any data type. Unlike Map, WeakMap holds keys weakly, so if a key object becomes unreachable elsewhere, it can be garbage collected automatically.


Why Use WeakMap?

  • Useful for private data storage tied to objects.
  • Prevents memory leaks by allowing garbage collection of unused keys.
  • Keys are not enumerable — you cannot iterate over a WeakMap.
  • Ideal for caching or associating metadata with objects without modifying them.

Syntax


Example 1: Basic Usage


Important Points About WeakMap

  • Only objects can be keys.
  • WeakMap methods include set(), get(), has(), and delete().
  • Keys are not iterable or enumerable.

Example 2: Using has() and delete()


Example 3: Private Data Encapsulation

In this example, age is private and cannot be accessed directly from outside the class.


WeakMap vs Map

  • WeakMap keys must be objects; Map keys can be any type.
  • WeakMap keys are weakly referenced and not enumerable.
  • Map keys are strongly referenced and enumerable.

Key Takeaways

  • Use WeakMap for storing key-value pairs with object keys only.
  • WeakMaps help avoid memory leaks through automatic garbage collection.
  • Suitable for private/internal data storage and caching.
  • WeakMap keys are not iterable.
Next : WeakSet