Map.prototype.delete()
A useful return value, which the delete operator on objects does not give you — that one reports whether deletion was ALLOWED, not whether anything was removed.
Demo
The pair is [did it delete, how many remain]. A present key gives true and the size drops; an absent key gives false and nothing changes. That boolean is genuinely useful — it lets you act on whether the entry existed without a separate has() call, which the delete operator on plain objects cannot do at all.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | any | yes | The key to remove, matched by SameValueZero. A missing key is not an error — it simply returns false. |
Return value
boolean — True if an entry was removed, false if the key was not there. clear() removes everything and returns undefined.
Common patterns
if (cache.delete(key)) log("evicted", key);
cache.clear();
const meta = new WeakMap(); meta.set(node, data);
Examples
Pitfalls
const m = new Map(); m.set(node, data); // node stays alive
const m = new WeakMap(); m.set(node, data);
const removed = map.clear();
const removed = map.size; map.clear();
for (const [k] of m) m.delete(otherKey);
for (const [k] of [...m]) m.delete(k);
const m = new Map([["a", 1]]); delete m["a"]; m.size
m.delete("a"); m.size
When to use
- Removing one entry, especially when you want to know it existed
- Cache eviction
- clear() to reset a Map without reallocating it
- Object keys that should be garbage collected → WeakMap
- Removing many entries by a predicate → rebuild from a filtered spread
- You want the removed value → get it first, delete returns only a boolean
Notes
FAQ
Because they answer different questions. The delete operator reports whether the property COULD be deleted — it is true even for a property that never existed. Map.delete reports whether an entry was actually removed, which is the useful answer.
delete {}.nope; // true new Map().delete("nope"); // false