JavaScript Reference ยท Collections
Map.prototype.has() and delete()
Reference for Map.prototype.has() and delete(): test whether a key exists, remove one entry, read the boolean results and clear a whole map.
map.has(key) returns true if the map contains an entry with that key, and false otherwise. map.delete(key) removes that entry and returns true if there was one to remove, or false if the key was not present.
Use has() instead of checking get() for undefined whenever a stored value could itself be undefined. To remove everything at once, use map.clear().
const tags = new Map([["a", 1], ["b", 2]]); tags.has("a"); // true tags.delete("a"); // true tags.has("a"); // false
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
map.has(key) map.delete(key) map.clear()
| Name | Description |
|---|---|
key |
The key to test for or to remove. Compared with "same value zero": like ===, but NaN equals NaN. |
Return value: has() and delete() return a boolean. clear() returns undefined.
Exceptions: none for ordinary use; calling the methods on a non-Map throws a TypeError.
Usage notes
has()is the reliable existence test.map.get(k) !== undefinedfails for entries whose value isundefined, andif (map.get(k))also fails for0,""andfalse.delete()reports what happened. Its result tells you whether anything was removed, which is useful for "remove if present" logic and for counting removals.- Deleting during iteration is safe. An entry removed before the loop reaches it is skipped. Entries added during the loop are visited, so a loop that keeps adding can run forever.
deleteis not the operator.delete map.keyanddelete map[key]act on object properties and do nothing to entries.- Order after re-adding. A deleted-then-added key goes to the end of the order.
clear()empties the same map. Other variables that refer to the map see it empty. Assignnew Map()instead if you want to leave the old map intact for other holders.- Both are fast. Lookups and deletions take roughly constant time regardless of size, which is the main performance reason to prefer a
Mapover searching an array.
Browser support
has(), delete() and clear() work in every current browser and in Node.js.