JavaScript weakMap set() Method

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: Usage of weakMap set()

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

WeakMap

WeakMap get()

WeakMap has()

WeakMap delete()