The map is basically a collection of elements where each element is stored as a Key, value pair. It can hold both objects and primitive values as either a key or a value. When we iterate over the map object it returns the key,value pair in the same order as inserted. The map has provided a method called map.clear() to remove the values inside a map. This method will remove every key/value pair and make the map totally empty.
syntax
map.clear(obj);
map.obj() takes an object as a parameter and removes each and every value so as to make it empty.
Example-1
In the following example, a map is created and 2 elements were passed to it. Before applying map.clear() method the size of the map object was two but after applying the size was zero.
<html> <body> <script> var myMap = new Map(); myMap.set(0, 'Tutorialspoint'); myMap.set(1, 'Tutorix'); document.write(myMap.size); document.write("</br>"); myMap.clear(); document.write(myMap.size); </script> </body> </html>
Output
2 0
Example-2
In the following example, a map is created and 4 elements were passed to it. Before applying map.clear() method the size of the map object was four but after applying the size was zero.
<html> <body> <script> var myMap = new Map(); myMap.set(0, 'India'); myMap.set(2, 'Australia'); myMap.set(3, 'England'); myMap.set(4, 'Newzealand'); document.write(myMap.size); document.write("</br>"); myMap.clear(); document.write(myMap.size); </script> </body> </html>
Output
4 0