Map.delete()

The Map.delete() method in JavaScript removes a specified element from a Map object using the given key. If the key exists in the map, the element is deleted and the method returns true. If the key does not exist, it returns false.

Syntax

</>
Copy
mapInstance.delete(key)

Parameters

ParameterDescription
keyThe key of the element to remove from the Map object.

Return Value

The delete() method returns true if the key existed in the Map and was deleted. Otherwise, it returns false.


Examples

1. Deleting an Existing Key

This example shows how to remove an existing key-value pair from a Map object.

</>
Copy
const myMap = new Map();
myMap.set('name', 'Arjun');
myMap.set('age', 25);

console.log(myMap.delete('name')); // true
console.log(myMap);

Output

true
Map { 'age' => 25 }
  1. The delete() method removes the 'name' key and returns true.
  2. After deletion, the map contains only one key-value pair.

2. Attempting to Delete a Non-Existing Key

If the specified key does not exist in the Map, delete() returns false.

</>
Copy
const myMap = new Map();
myMap.set('name', 'Arjun');

console.log(myMap.delete('age')); // false

Output

false

Since 'age' was not in the map, delete() returns false and does not modify the map.

3. Checking Key Existence Before Deleting

Use the has() method to check if a key exists before attempting to delete it.

</>
Copy
const myMap = new Map([
  ['name', 'Arjun'],
  ['age', 25]
]);

if (myMap.has('age')) {
    myMap.delete('age');
}

console.log(myMap);

Output

Map { 'name' => 'Arjun' }

The key 'age' was checked and then deleted, leaving only the 'name' key in the map.

4. Deleting Keys with Complex Data Types

Keys in a Map can be objects, functions, or other complex data types. This example demonstrates deleting an object key.

</>
Copy
const objKey = { id: 1 };
const myMap = new Map();

myMap.set(objKey, 'Stored with object key');

console.log(myMap.delete(objKey)); // true
console.log(myMap);

Output

true
Map(0) {}

The object key objKey is deleted, leaving an empty Map.