CKTIS / JavaScript
WeakMap.prototype.delete(): Remove an entry by key
Remove an entry from a `WeakMap` and use the boolean result to tell whether the entry was actually removed.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
weakMap.delete(key)WeakMap.prototype.delete is an instance method. Call weakMap.delete(key) to remove the entry for key from that map. It returns true only if it removed an existing entry, even if the stored value was undefined. If there is no entry, it returns false.
Keys are matched by identity: two separate objects with the same properties are different keys. ECMAScript 2024 allows objects and non-registered symbols, such as those created with Symbol(). Support for symbol keys varies by runtime. For an invalid key, such as a string or a symbol from Symbol.for(), delete() returns false, whereas set() throws a TypeError. Calling the method with an invalid this, as in WeakMap.prototype.delete.call({}, key), also throws a TypeError.
The method removes the association immediately. It does not change the key object, remove any of its properties like the delete operator, or force garbage collection. Use it when the stored association is no longer needed but the key is still available.
Examples
{
const weakMap = new WeakMap();
const key = { id: 1 };
weakMap.set(key, undefined);
console.log(weakMap.delete({ id: 1 }));
console.log(weakMap.delete(key));
console.log(weakMap.has(key));
console.log(weakMap.delete(key));
console.log(weakMap.delete("id"));
}Result
false true false false false
The new `{ id: 1 }` object does not match the stored key. The original `key` removes the entry even though its value is `undefined`. The `has()` check, the repeated deletion, and the attempt with a string key all return `false`.
Related lessons
- JavaScript · Lesson 35 · Basic · Version: 4
- JavaScript · Lesson 37 · Basic · Version: 4
- JavaScript · Lesson 4 · Intermediate · Version: 3
- JavaScript · Lesson 10 · Intermediate · Version: 3
Sources
- ECMAScript 2024 Language Specification — WeakMap.prototype.delete (key)
- ECMAScript Language Specification — WeakMap.prototype.delete (key)
- ECMAScript 2024 Language Specification — CanBeHeldWeakly (v)
- ECMAScript 2024 Language Specification — WeakMap Objects
- ECMAScript 2024 Language Specification — The delete Operator
- MDN — WeakMap.prototype.delete()
- MDN — WeakMap browser compatibility