Open In App

JavaScript Map delete() Method

JavaScript Map.delete() method is used to delete the specified element among all the elements that are present in the map. The Map.delete() method takes the key that 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:

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.




// creating a map object
let my_map = new Map();
 
// Adding [key, value] pair to the map
my_map.set(1, 'first');
my_map.set(2, 'second');
my_map.set(3, 'third');
my_map.set(4, 'fourth');
 
// will display true as key '3'
// is present and its associated
// element is removed as well
console.log(my_map.delete(3));
 
 
// elements left in the map after deletion
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. 




// creating a map object
let my_map = new Map();
 
// Adding [key, value] pair to the map
my_map.set(1, 'first');
my_map.set(2, 'second');
my_map.set(3, 'third');
my_map.set(4, 'fourth');
 
// will display false as key '5'
// is not present and its associated
// element is removed as well
console.log(my_map.delete(5))
 
// elements left in the map after deletion
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:

Exceptions:

We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Complete Reference article.

Supported Browser:


Article Tags :