.delete()
Removes the entry associated with a given key from a Map
object.
Syntax
The .delete()
method accepts a key
parameter and returns true
if the deletion was successful. Otherwise, if the key
does not exist, false
is returned.
map.delete(key);
Example
Data can be removed from a Map
object using the .delete()
method.
const fruits = new Map([['Apples', 5],['Oranges', 8],]);console.log(fruits.delete('Oranges')); // Output: trueconsole.log(fruits.delete('Strawberries')); // Output: false
The first .delete()
statement returns true
because fruits
contain an entry with Oranges
as a key and has successfully removed it. The second statement returns false
because an entry with the Strawberries
key does not exist in fruits
.
Codebyte Example
In the code below, a new inventory Map
of consumable construction supplies catalogs the current quantities on hand. In this example:
- Bob will log that he used a roll of tape by updating its value using the
.set()
method. - Bob noticed he used the last roll so he will remove it from the map using the
.delete()
method. He feels confident it worked correctly due totrue
being displayed in the console output. - Manny notices that there are no Tape Rolls left, but he doesn’t know Bob already called the
.delete()
method. He attemps to delete it and notices the console outputsfalse
.
All contributors
- dghalbr2 total contributions
- BrandonDusch580 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.