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
myMap.set("name", "Arjun")andmyMap.set("age", 25)add key-value pairs to theMap.myMap.sizereturns the number of elements in theMap.myMap.clear()removes all entries from theMap.- After calling
clear(),myMap.sizeis0.
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
- A
Mapis created with two entries. myMap.sizeis checked before and after callingclear().- After calling
clear(), theMapbecomes empty.
