CKTIS / JavaScript
WeakMap.prototype.delete() — remove an entry
Call `weakMap.delete(key)` to remove the entry for a given key. It returns `true` if it removed an entry and `false` if it did not.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
weakMap.delete(key)WeakMap.delete is shorthand for the instance method WeakMap.prototype.delete. Call it as weakMap.delete(key), not as a static method on the WeakMap constructor. It removes the key–value association from that map only. Unlike the delete operator, it does not remove an object property.
A result of true means an entry existed and was removed, even if its value was undefined. A missing entry gives false. Object keys are matched by identity: two separate objects with the same properties do not match. After deletion, weakMap.has(key) returns false unless you add an entry for that key again.
ECMAScript 2024 allows objects and non-registered symbols such as Symbol() as keys, but not symbols from Symbol.for(). Support for symbol keys varies by runtime. On a valid instance, delete() returns false for an invalid key such as a string or when the argument is omitted; set() throws TypeError for an invalid key. Calling delete() without a valid instance as this also throws TypeError.
A WeakMap does not keep an object alive merely because it is a key. Explicit deletion removes the entry immediately, even if your code still holds a reference to the key. It does not destroy the object or force garbage collection.
Examples
{
const notes = new WeakMap();
const key = { id: 1 };
notes.set(key, undefined);
console.log(notes.delete({ id: 1 }));
console.log(notes.delete(key));
console.log(notes.has(key));
console.log(notes.delete(key));
console.log(notes.delete("id"));
}Result
false true false false false
The separate `{ id: 1 }` object does not match `key`. Deleting with `key` returns `true` despite the stored value being `undefined`. Then `has()`, a second deletion, and a deletion attempt with a string key each return `false`.
Related lessons
- JavaScript · Lesson 18 · Basic · Version: 4