JavaScript weakMap get() Method

The JavaScript weakMap get method is used to retrieve the value of a specified key of an element from a WeakMap object.

Syntax

weakMap.get(key);

Parameters

key:  The key of the element to return from the WeakMap object.

Return Value

It returns the value of a specified key. If the key can not be found, undefined is returned.

Example 1: How to Use JavaScript weakMap get() 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

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

weakMap.set(key1, 79);

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

Output

79
undefined

In the above example, it returns undefined because we haven’t set the value of key 2.

Browser Compatibility

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

That’s it!

Related posts

JavaScript WeakMap

JavaScript WeakMap set() Method

JavaScript WeakMap has() Method

JavaScript WeakMap delete() Method

Leave a Comment