JavaScript Map.delete() method is used to delete the specified element among all the elements which are present in the map. The Map.delete() method takes the key which needs to be removed from the map, thus removing the element associated with that key and returning true. If the key is not present then it returns false.
Syntax:
my_map.delete(key)
Parameters Used:
- key: The element associated with this key is to be removed from the map
Return value: The Map. delete() method returns true if the key is present whose associated element is to be removed which is passed as an argument, otherwise returns false.
Example 1: The key ‘3’ is present in the map hence element associated with it is removed and returns true.
javascript
let my_map = new Map();
my_map.set(1, 'first' );
my_map.set(2, 'second' );
my_map.set(3, 'third' );
my_map.set(4, 'fourth' );
console.log(my_map. delete (3));
console.log( "key-value pair of the map" ,
" after deletion-" );
my_map.forEach( function (item, key, mapObj) {
console.log(key.toString(), ":" ,
" " , item.toString());
});
|
Output:
true
key-value pair of the map after deletion-
1: first
2: second
4: fourth
Example 2: The key ‘5’ is not present in the map hence it returns false.
javascript
let my_map = new Map();
my_map.set(1, 'first' );
my_map.set(2, 'second' );
my_map.set(3, 'third' );
my_map.set(4, 'fourth' );
console.log(my_map. delete (5))
console.log( "key-value pair of the map" ,
" after deletion-" );
my_map.forEach( function (item, key, mapObj) {
console.log(key.toString(), ":" , " " ,
item.toString());
});
|
Output:
false
key-value pair of the map after deletion-
1: first
2: second
3: third
4: fourth
Applications:
- Map.delete() is used to delete an element associated with the key among all the elements present in the map.
Exceptions:
- If the key passed as an argument to the function is not present in the map then it returns false. Basically, it neither throws any exception nor does it have any error.
We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Complete Reference article.
Supported Browser:
- Chrome 38 and above
- Edge 12 and above
- Firefox 13 and above
- Internet Explorer 11 and above
- Opera 25 and above
- safari 8 and above