To check if a map is empty in JavaScript, you can use the size property. This property returns the number of elements in the map.
We can check if a map is empty in JavaScript using the size property, which returns 0 if the map contains no elements and a positive number otherwise.
For example,
myMap
. In this example, the map has string keys and integer values.size
property to check if the map is empty. The size
property returns the number of elements in the map.const myMap = new Map();
// Check if the map is empty using size property
const isEmpty = myMap.size === 0;
// Print the result
console.log(`Is the map empty? ${isEmpty ? 'Yes' : 'No'}`);
Is the map empty? Yes
We can check if a non-empty map is empty in JavaScript using the size property, which returns a positive number if the map contains elements.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.size
property to check if the map is empty. The size
property returns the number of elements in the map.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Check if the map is empty using size property
const isEmpty = myMap.size === 0;
// Print the result
console.log(`Is the map empty? ${isEmpty ? 'Yes' : 'No'}`);
Is the map empty? No
We can check if a map is empty in JavaScript after clearing its elements using the size property, which returns 0 if the map contains no elements.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.clear
method to remove all elements from the map, making it empty.size
property to check if the map is empty after clearing. The size
property returns the number of elements in the map.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Clear the map
myMap.clear();
// Check if the map is empty using size property
const isEmpty = myMap.size === 0;
// Print the result
console.log(`Is the map empty? ${isEmpty ? 'Yes' : 'No'}`);
Is the map empty? Yes
In this tutorial, we learned How to Check if a Map is Empty in JavaScript language with well detailed examples.