The delete() method of the Map object in JavaScript removes the specified element from a Map object by key and returns a boolean indicating whether the element was successfully removed.
The syntax of Map.delete() method is:
mapInstance.delete(key)
This delete() method of Map returns true if an element in the Map object existed and has been removed, or false if the element does not exist. map.has(key) will return false afterwards.
Parameter | Optional/Required | Description |
---|---|---|
key | required | The key of the element to remove from the Map. |
Map.delete() returns value of type boolean
.
In JavaScript, we can use the delete()
method to remove a specific element from a Map object by key.
For example,
map
with initial key-value pairs.delete()
method to remove the element with the key 'a' from the map
.delete()
method and the updated map
to the console using console.log()
.const map = new Map([['a', 1], ['b', 2]]);
const result = map.delete('a');
console.log(result); // true
console.log(map);
true Map { 'b' => 2 }
In JavaScript, we can use the delete()
method to try removing an element that is not present in the Map object, which will return false.
For example,
map
with initial key-value pairs.delete()
method to try removing the element with the key 'c' from the map
.delete()
method and the updated map
to the console using console.log()
.const map = new Map([['a', 1], ['b', 2]]);
const result = map.delete('c');
console.log(result); // false
console.log(map);
false Map { 'a' => 1, 'b' => 2 }
In JavaScript, we can use the delete()
method to remove an element with an object key from a Map object.
For example,
map
with initial key-value pairs where keys are objects.delete()
method to remove the element with the key key1
from the map
.delete()
method and the updated map
to the console using console.log()
.const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
[key1, 'value1'],
[key2, 'value2']
]);
const result = map.delete(key1);
console.log(result); // true
console.log(map);
true Map { { id: 2 } => 'value2' }
In this JavaScript tutorial, we learned about delete() method of Map: the syntax and few working examples with output and detailed explanation for each example.