JavaScript WeakMap (original) (raw)

Last Updated : 01 Mar, 2025

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.

**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

Components of a Weak Map

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;

`

Functions present in Weak Map

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

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.