JavaScript - Map.clear() Method
The Map.clear() method in JavaScript is used to remove all elements from a Map object. This method returns nothing as result (i.e. undefined) instead, it removes all the elements from the Map object.
Syntax
Following is the syntax of JavaScript Map.clear() method −
clear()
Parameters
This method does not accept any parameters.
Return value
This method returns nothing (i.e. undefined).
Examples
Example 1
In the following example, we are using the JavaScript Map.clear() method to remove all elements from this map −
<html>
<body>
<script>
let map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
document.write(map.size, "<br>"); // Output: 2
map.clear();
document.write(map.size); // Output: 0
</script>
</body>
</html>
As we can see in the output, it removed all the elements.
Example 2
In this example, we have initialized a Map with three key-value pairs using an array of arrays. Later, we used the clear() method to remove all the entries in it −
<!DOCTYPE html>
<html>
<body>
<script>
const myMap = new Map([
['apple', 5],
['banana', 8],
['orange', 3]
]);
document.write(myMap.size, "<br>"); // Output: 3
myMap.clear();
document.write(myMap.size); // Output: 0
</script>
</body>
</html>
As we can see in the output, the size of the Map after using the clear() method is 0.