JavaScript Map delete() Method (original) (raw)

Last Updated : 19 Sep, 2024

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:

**Return value:

**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

**Supported Browsers: