Map.clear()

The Map.clear() method in JavaScript is used to remove all key-value pairs from a Map object. After calling clear(), the Map will be empty.

Syntax

</>
Copy
map.clear()

Parameters

The clear() method does not take any parameters.

Return Value

The clear() method does not return a value (undefined). It simply removes all elements from the Map.


Examples

1. Clearing a Map

This example demonstrates how to remove all elements from a Map using clear().

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

console.log(myMap.size); // Output: 2

myMap.clear();

console.log(myMap.size); // Output: 0

Output

2
0
  1. myMap.set("name", "Arjun") and myMap.set("age", 25) add key-value pairs to the Map.
  2. myMap.size returns the number of elements in the Map.
  3. myMap.clear() removes all entries from the Map.
  4. After calling clear(), myMap.size is 0.

2. Checking If a Map is Empty After clear()

After using clear(), the Map is empty, and size returns 0.

</>
Copy
const myMap = new Map([
    ["a", 1],
    ["b", 2]
]);

console.log('Initial Map:');
console.log(myMap.size > 0 ? "Map is not empty" : "Map is empty");

myMap.clear();

console.log('\nAfter Clearing:');
console.log(myMap.size > 0 ? "Map is not empty" : "Map is empty");

Output

Initial Map:
Map is not empty

After Clearing:
Map is empty
  1. A Map is created with two entries.
  2. myMap.size is checked before and after calling clear().
  3. After calling clear(), the Map becomes empty.