Open In App

JavaScript WeakMap

Last Updated : 01 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A WeakMap in JavaScript is a collection of key-value pairs where the keys are objects, and the values can be any arbitrary value. Unlike regular maps, WeakMap keys are weakly referenced, meaning they don’t prevent garbage collection.

  • The keys in a WeakMap can be automatically removed when no longer in use, helping save memory.
  • You can’t loop through the keys or values in a WeakMap.

Syntax

const weakmap=new WeakMap()

To create a new weak map, the constructor function of the inbuilt WeakMap class is invoked with the help of the new keyword. This initiates a weak map object that can be used to invoke various properties present in itself as it is a class.

How a Weak Map Works

  • In a WeakMap, the keys are weakly referenced, meaning they do not prevent garbage collection. If there are no other references to a key, it can be collected as garbage.
  • Only objects can be used as keys in a WeakMap. Primitive values like strings or numbers cannot be used as keys.
  • You cannot iterate over the keys or values in a WeakMap. Methods like forEach() and keys() are not available.
  • When a key is garbage collected, its corresponding value is automatically removed from the WeakMap, ensuring there are no memory leaks.
  • WeakMap is often used to create private properties for objects, as it allows storing private data without exposing it to outside access.

Components of a Weak Map

  • Keys: The keys in a WeakMap must be objects. Primitive values like strings, numbers, or booleans cannot be used as keys.
  • Values: The values in a WeakMap can be any type of data, including primitives or objects, and are associated with the keys.
  • Garbage Collection: The keys in a WeakMap are weakly referenced, meaning that if there are no other references to a key object, it can be garbage collected along with its associated value.
  • No Iteration: Unlike regular maps, a WeakMap does not allow iteration (such as using forEach() or keys()) because of the weak references to keys.
  • Size: There is no direct way to check the size of a WeakMap. Since the garbage collector may remove keys at any time, the size is not a reliable property to access.

Implementation of a Weak Map

Here’s a simple example demonstrating how to use a WeakMap in JavaScript. It shows how to associate object keys with values and how the garbage collector can remove key-value pairs when the key is no longer referenced.

JavaScript
let weakMap = new WeakMap();

let obj1 = { name: "Pranjal" };
let obj2 = { name: "Pranav" };

weakMap.set(obj1, "Engineer");
weakMap.set(obj2, "Designer");

console.log(weakMap.get(obj1)); 
console.log(weakMap.get(obj2)); 


obj2 = null;

Output
Engineer
Designer
  • A WeakMap is initialized with let weakMap = new WeakMap();. This will hold key-value pairs where the keys must be objects.
  • Two objects, obj1 and obj2, are created and used as keys in the WeakMap. obj1 is associated with the value “Engineer” and obj2 with “Designer” using weakMap.set().
  • The values associated with obj1 and obj2 are accessed using weakMap.get(). The console logs will show “Engineer” for obj1 and “Designer” for obj2.
  • When obj2 is set to null, it no longer has a reference in the code. This allows the WeakMap to potentially remove obj2 and its associated value from memory since the key (obj2) is no longer referenced elsewhere.
  • Since WeakMap uses weak references for keys, obj2 and its associated value may be garbage collected after obj2 = null, freeing up memory.

Functions present in Weak Map

  • set(key, value): Adds a key-value pair to the WeakMap. The key must be an object.
  • get(key): Retrieves the value associated with the given key. If the key does not exist, it returns undefined.
  • has(key): Checks if a specific key exists in the WeakMap. Returns true if the key is present, otherwise false.
  • delete(key): Removes the specified key and its associated value from the WeakMap. Returns true if the key was successfully removed, otherwise false.
  • clear(): Clears all key-value pairs from the WeakMap. However, it is rarely used in practice since WeakMap entries are automatically removed when keys are garbage collected.

Coding Problems on WeakMap

Background working of WeakMap

A WeakMap stores key-value pairs where the keys are objects. If there are no other references to a key, it can be garbage collected, and the entry in the WeakMap will be removed automatically. Unlike Map, you can’t loop through a WeakMap because keys can be removed at any time. Only objects can be used as keys, making it memory-efficient for temporary data storage without blocking object cleanup.

Advantages of Weak Map

  • Memory Efficiency: Automatically frees memory by allowing garbage collection of unused keys.
  • Garbage Collection: Keys can be garbage-collected when there are no other references to them.
  • No Enumeration: Does not allow iteration over keys or values, protecting privacy.
  • Key Constraints: Only objects can be used as keys, preventing issues with primitive types.
  • Efficient Memory Management: Ideal for scenarios like caching, where unused data is automatically removed.

Conclusion

In conclusion, WeakMap in JavaScript is a memory-efficient way to store key-value pairs where the keys are objects. Its weak references allow for automatic garbage collection of keys when no longer in use, making it ideal for managing memory and preventing leaks. While it lacks iteration methods, it’s a useful tool for optimizing memory in specific use cases like private data storage.



Next Article

Similar Reads