JavaScript – Delete a Key from Map
To delete a key from Map in JavaScript, call delete() method on this map and pass the specific key as argument to it.
delete() method returns a boolean value. The return value is true
if the key is successfully removed from the map, else, false
.
Syntax
The syntax to remove/delete a specific key key
from a Map map
using delete() method is
map.delete(key)
Examples
In the following example, we take a Map with keys 'a'
, 'b'
, and 'c'
. We shall delete the key 'b'
using delete() method.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var map1 = new Map([
['a', 10],
['b', 20],
['c', 30]
]);
var result = map1.delete('b');
var displayOutput = 'Is the key removed? ' + result + '\n\n';
displayOutput += 'Map contents :\n'
map1.forEach (function(value, key) {
displayOutput += key + ' - ' + value + '\n';
});
document.getElementById('output').innerHTML += displayOutput;
</script>
</body>
</html>
If the specified key is not present, then delete() method does nothing and returns false
.
In the following example, we try to delete a key 'x'
which is not present in the Map map1
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var map1 = new Map([
['a', 10],
['b', 20],
['c', 30]
]);
var result = map1.delete('x');
var displayOutput = 'Is the key removed? ' + result + '\n\n';
displayOutput += 'Map contents :\n'
map1.forEach (function(value, key) {
displayOutput += key + ' - ' + value + '\n';
});
document.getElementById('output').innerHTML += displayOutput;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to delete a specific key from a Map in JavaScript using delete() method, with examples.