JavaScript Map delete()
Syntax & Examples

Map.delete() method

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.


Syntax of Map.delete()

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.

Parameters

ParameterOptional/RequiredDescription
keyrequiredThe key of the element to remove from the Map.

Return Type

Map.delete() returns value of type boolean.



✐ Examples

1 Using delete() to remove an element from a Map

In JavaScript, we can use the delete() method to remove a specific element from a Map object by key.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the delete() method to remove the element with the key 'a' from the map.
  3. Log the result of the delete() method and the updated map to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2]]);
const result = map.delete('a');
console.log(result); // true
console.log(map);

Output

true
Map { 'b' => 2 }

2 Using delete() to attempt removing a non-existent element

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,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the delete() method to try removing the element with the key 'c' from the map.
  3. Log the result of the delete() method and the updated map to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2]]);
const result = map.delete('c');
console.log(result); // false
console.log(map);

Output

false
Map { 'a' => 1, 'b' => 2 }

3 Using delete() with a Map of objects

In JavaScript, we can use the delete() method to remove an element with an object key from a Map object.

For example,

  1. Create a new Map object map with initial key-value pairs where keys are objects.
  2. Use the delete() method to remove the element with the key key1 from the map.
  3. Log the result of the delete() method and the updated map to the console using console.log().

JavaScript Program

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);

Output

true
Map { { id: 2 } => 'value2' }

Summary

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.