Open In App

How to understand WeakMap in JavaScript ?

Last Updated : 09 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The WeakMap object stores key/value pairs. The keys should be objects, and also the value may be anything. In JavaScript, a map API may be engineered with 2 arrays, one for keys and one for values that are shared by the four API functions. Setting parts on this map would entail at the same time inserting a key and value onto the top of every one of these arrays. As a result, the key and value indices would correspond to each array. 

To get values from the map, ingeminate through all keys till a match is found, then use the index of that match to extract the associated item from the array of values. The excellence between Map and keys is that keys should be objects and are solely debile referenced. This suggests that if there aren’t any extra robust references to the key, the garbage collector can delete the part in WeakMap.

Syntax:

new WeakMap([iterable])

Parameter: The WeakMap Object() accepts an argument that will be any iterable object. For example, an Array that contains key/value pairs as two-element arrays.

Example 1: Obtaining a value related to the key – Use the .get() function to retrieve a value connected with the key. If no value is connected with the key, it returns undefined.

Javascript




const obj1 = {},
obj2 = {};
 
const weakmap = new WeakMap([[obj1, 100]]);
 
// Printing values
console.log(weakmap.get(obj1)); // 100
console.log(weakmap.get(obj2)); // undedfined


Output:

100
undefined

Example 2: Putting a value on the key – Use the .set() function to assign a value to the key. It returns the WeakMap object, that permits you to chain.set() commands.

Javascript




const obj1 = {};
 
const weakmap = new WeakMap();
weakmap.set(obj1, "gfg");
 
// Printing value
console.log(weakmap.get(obj1));


Output:

gfg

Example 3: Validating whether there is an element with the key – Use the .has() function to envision if an element with an exact key exits in a WeakMap. If it presents, it returns true otherwise, it returns false.

Javascript




const obj1 = {},
obj2 = {};
 
const weakmap = new WeakMap([[obj1, "gfg"]]);
 
// Printing values
console.log(weakmap.has(obj1)); // true
console.log(weakmap.has(obj2)); // false


Output:

true
false

Example 4: Using the key to remove an ElementTo delete an element with an exact key, use the .delete() method. It returns true if the component existed and was removed otherwise, it returns false.

Javascript




const obj1 = {};
 
const weakmap = new WeakMap([[obj1, "gfg"]]);
 
// Printing values
console.log(weakmap.delete(obj1)); // true
console.log(weakmap.has(obj1)); // false


Output:

true
false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads