JavaScript WeakMap

JavaScript WeakMap is used to store a collection of key-value pairs where keys are weakly referenced. The keys are objects, and values are arbitrary values. Keep in mind that in weakMap, keys are not enumerable.

Syntax

new WeakMap()

new WeakMap(iterable)

Parameters

iterable:  It has two elements, the first is key, and the second is value.

Example 1: How to Use JavaScript WeakMap

let weakMap = new WeakMap();
let key1 = {};
let key2 = {};
 
weakMap.set(key1, "Ronaldo");
weakMap.set(key2, "Messi");

console.log(weakMap.get(key1));
console.log(weakMap.get(key2));

Output

Ronaldo
Messi

JavaScript WeakMap Methods

Methods Description
delete() It deletes an element with a specific key.
get() It is used to return the value associated with the key.
has() It is used to determine whether a specified key exists within the WeakMap.
set() It assigns a value to the key.

In WeakMap, Iteration and keys(), entries(), values() methods are not supported.

Leave a Comment