Open In App

JavaScript Map delete() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • 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




// 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. 

javascript




// 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:

  • 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


Last Updated : 13 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads