JavaScript Map size
Syntax & Examples

Map.size property

The size property of the Map object in JavaScript returns the number of key/value pairs in the Map object.


Syntax of Map.size

The syntax of Map.size property is:

Map.prototype.size

This size property of Map returns the number of key/value pairs in the Map object.

Return Type

Map.size returns value of type number.



✐ Examples

1 Using size to get the number of elements in a Map

In JavaScript, we can use the size property to get the number of key/value pairs in a Map object.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the size property to get the number of key/value pairs in the map.
  3. Log the result to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const size = map.size;
console.log(size);

Output

3

2 Using size after adding an element to a Map

In JavaScript, we can use the size property to get the number of key/value pairs in a Map object after adding an element.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the set() method to add a new key-value pair to the map.
  3. Use the size property to get the updated number of key/value pairs in the map.
  4. Log the result to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2]]);
map.set('c', 3);
const size = map.size;
console.log(size);

Output

3

3 Using size after removing an element from a Map

In JavaScript, we can use the size property to get the number of key/value pairs in a Map object after removing an element.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the delete() method to remove a key-value pair from the map.
  3. Use the size property to get the updated number of key/value pairs in the map.
  4. Log the result to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
map.delete('a');
const size = map.size;
console.log(size);

Output

2

Summary

In this JavaScript tutorial, we learned about size property of Map: the syntax and few working examples with output and detailed explanation for each example.