Map.size
The Map.size
property in JavaScript returns the number of key-value pairs present in a Map
object. This property is read-only and provides the count of elements stored in the Map
.
Syntax
</>
Copy
map.size
Return Value
The size
property returns a number indicating the count of key-value pairs in the Map
.
Examples
1. Getting the Size of a Map
This example demonstrates how to retrieve the size of a Map
object.
</>
Copy
const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
console.log(map.size);
Output
3
- The
Map
contains three key-value pairs. map.size
returns3
, indicating the total number of elements in theMap
.
2. Checking Size After Deleting Elements
The size of a Map
is updated dynamically when elements are removed.
</>
Copy
const map = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
console.log(map.size); // Initial size
map.delete('b'); // Removing a key-value pair
console.log(map.size);
Output
3
2
- The initial size of the
Map
is3
. - After deleting the key
'b'
, the size is reduced to2
.
3. Using size
to Validate a Map
You can use size
to check if a Map
is empty.
</>
Copy
const map = new Map();
if (map.size === 0) {
console.log("The Map is empty.");
} else {
console.log("The Map has elements.");
}
map.set('x', 10);
console.log('After adding an element...')
if (map.size === 0) {
console.log("The Map is empty.");
} else {
console.log("The Map has elements.");
}
Output
The Map is empty.
After adding an element...
The Map has elements.
- Before adding an element,
map.size === 0
, indicating an emptyMap
. - After adding
'x'
, thesize
becomes greater than0
, meaning theMap
is no longer empty.
4. Understanding size
with Duplicate Keys
The Map
structure only counts unique keys, so updating an existing key does not increase the size
.
</>
Copy
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map.size); // Initial size
map.set('key1', 'newValue1'); // Updating existing key
console.log(map.size);
Output
2
2
- The initial size of the
Map
is2
. - Updating
'key1'
does not increase thesize
because keys in aMap
are unique.