Skip to content
Tutorials Center
My learning

Topics

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().

JavaScript
const tags = new Map([["a", 1], ["b", 2]]);
tags.has("a");      // true
tags.delete("a");   // true
tags.has("a");      // false

Try it

JS Checking and removing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Deleting while iterating

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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) !== undefined fails for entries whose value is undefined, and if (map.get(k)) also fails for 0, "" and false.
  • 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.
  • delete is not the operator. delete map.key and delete 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. Assign new 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 Map over searching an array.

Browser support

has(), delete() and clear() work in every current browser and in Node.js.