Open In App

What is the use of the Map.prototype.clear method in JavaScript Maps ?

In JavaScript, the Map.prototype.clear method is used to remove all key-value pairs from a Map, effectively making the Map empty. It does not take any arguments and does not return any value.

Syntax:

myMap.clear();

Example: Here, a map object “myMap” has been created with a single [key, value] pair, and the Map.clear() method is used to remove the [key, value] pair from “myMap”. myMap.size() is used to check the number of [key, value] pairs belonging to the map object.




// Creating a map object
let myMap = new Map();
 
// Adding [key, value] pair to the map
myMap.set(0, 'geeksforgeeks');
 
// Displaying the number of
// [key, value] pairs the map has
console.log(myMap.size);
 
// Removing the [key, value] pairs of
// the map using Map.clear() method
myMap.clear();
 
// Displaying the number of
// [key, value] pairs the map has
console.log(myMap.size);

Output
1
0
Article Tags :