Check if a Map is Empty in JavaScript?
These are the following ways to check whether the given map is empty or not:
1. Using size property - Mostly Used
you can check if a Map is empty by using its size property. The size property returns the number of key-value pairs in the Map. If the size is 0, the Map is empty.
const m = new Map();
if (m.size === 0) { console.log("Empty") }
else { console.log("Not Empty") }
Output
Empty
2. Using for ... of Loop
You can use a for...of loop to attempt to iterate over the Map's entries. If the loop doesn't execute, the Map is empty.
const myMap = new Map();
let isEmpty = true;
for (let [k, val] of myMap) {
isEmpty = false;
break;
}
if (isEmpty) { console.log("Empty") }
else { console.log("Not Empty") }
Output
Empty
3. Using the keys() Method
The keys() method of a Map returns an iterator for the keys in the Map. If the Map is empty, the iterator will not yield any values.
let mp = new Map();
let res = mp.keys().next().done;
if (res) { console.log("Empty") }
else { console.log("Not Empty") }
Output
Empty
4. Using entries() Method
Similar to keys(), the entries() method of a Map returns an iterator for the key-value pairs in the Map. You can check whether the iterator has any entries.
let mp = new Map();
let res = mp.entries().next().value;
if (res) { console.log("Not Empty") }
else { console.log("Empty") }
Output
Empty
5. Using ._isEmpty() Lodash Method
This ._isEmpty() Lodash Method is used to check whether the given data having any data type is empty or not and it return boolean value. if it is empty it return true else false.
let _ = require("lodash")
let mp = new Map();
if (_.isEmpty(mp)) { console.log("Empty") }
else { console.log("Not Empty") }
Output:
Empty