JavaScript weakMap delete() Method

JavaScript weakMap delete() method is used to remove(delete) specified element from a weakMap object. 

Syntax

weakMap.delete(key);

Parameters

key: The key of the element that is going to be deleted from the weakMap object.

Return Value

It returns true if an element in the weakMap object has been deleted successfully, otherwise false.

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

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

weakMap.set(key1, 79);
weakMap.set(key2, 'askJavascript');


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

Output

true
true

Example 2

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

weakMap.set(key1, 79);

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

console.log(weakMap.has(key1));

Output

true
false
false

In this example, key1 has been deleted successfully, so it returns true, but key2 has not been set at the end of the weakMap object, so it returns false. Also, we have checked again using the has() method whether key1 exists in the weakMap, but it returns false because we have already deleted it.

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 get() Method

JavaScript WeakMap has() Method

Leave a Comment