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
  1. The Map contains three key-value pairs.
  2. map.size returns 3, indicating the total number of elements in the Map.

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
  1. The initial size of the Map is 3.
  2. After deleting the key 'b', the size is reduced to 2.

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.
  1. Before adding an element, map.size === 0, indicating an empty Map.
  2. After adding 'x', the size becomes greater than 0, meaning the Map 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
  1. The initial size of the Map is 2.
  2. Updating 'key1' does not increase the size because keys in a Map are unique.