JavaScript weakMap set() Method

The JavaScript weakMap set method is used to set a new element with a specified key and value to a WeakMap object

Syntax

weakMap.set(key, value);

Parameters

  1. key: It represents the object that will be used as the key in the WeakMap.
  2. value: It corresponds to the value associated with the key in the WeakMap.

Return Value

It returns a weakMap object.

Example 1: How to Use JavaScript weakMap set() Method

let weakMap = new WeakMap();
let key1 = {};
let key2 = {};

weakMap.set(key1, "Taylor Swift");
weakMap.set(key2, "Selena Gomez");

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

Output


Taylor Swift
Selena Gomez

Example 2: WeakMap object in chainable form

let weakMap = new WeakMap();
let key1 = {};
let key2 = {};

weakMap.set(key1, "Taylor Swift").set(key2, "Selena Gomez");

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

Output

Taylor Swift
Selena Gomez

Browser Compatibility

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

That’s it!

Related posts

JavaScript WeakMap

JavaScript WeakMap get() Method

JavaScript WeakMap has() Method

JavaScript WeakMap delete() Method

Leave a Comment