What is a WeakMap Object in JavaScript ?
Last Updated :
31 Jan, 2024
WeakMap
is a collection of key-value pairs where keys must be objects, and values can be any values. Unlike a regular Map
, it holds weak references to keys, allowing them to be garbage-collected if no other references exist. It is often used to associate private data with objects without causing memory leaks and lacks methods for direct iteration to maintain privacy.
Example: Here, the key1
and key2
objects are used as keys in the WeakMap
. If there are no external references to key1
, it becomes eligible for garbage collection, and the corresponding entry in the WeakMap
will be automatically removed.
Javascript
const myWeakMap = new WeakMap();
const key1 = {};
const key2 = {};
myWeakMap.set(key1, 'Value for key1' );
myWeakMap.set(key2, 'Value for key2' );
console.log(myWeakMap.get(key1));
console.log(myWeakMap.get(key2));
console.log(myWeakMap.get(key1));
|
Output
Value for key1
Value for key2
Value for key1
Share your thoughts in the comments
Please Login to comment...