- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to remove all the elements from a map in JavaScript?
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