Last updated: Mar 2, 2024
Reading timeยท3 min
Use the size
property to get the length of a Map, e.g.
console.log(map.size)
.
The size
property returns the number of elements in the Map
object. When
accessed on an empty Map
, the size
property returns 0
.
const map = new Map(); map.set('name', 'bobby'); map.set('age', 30); map.set('country', 'Chile'); console.log(map.size); // ๐๏ธ 3
We used the
Map.size
property to get the number of key-value pairs in the Map
.
length
property and returns an integer representing how many items the Map
contains.As opposed to the array's length
property, the size
property is read-only
and can't be changed by the user.
const map = new Map(); map.set('name', 'Tom'); console.log(map.size); // ๐๏ธ 1 map.size = 5; console.log(map.size); // ๐๏ธ 1
Even though we tried to set the size of the Map
, we were unable to.
This is not the case when using the array's length
property.
const arr = ['a', 'b', 'c']; console.log(arr.length); // ๐๏ธ 3 // ๐๏ธ set the array's length to 1 arr.length = 1; console.log(arr.length); // ๐๏ธ 1 // ๐๏ธ updating the length removed 2 elements from the array. console.log(arr); // ๐๏ธ ['a']
The code sample shows that we can update the array's length and contents by
using its length
property.
As expected, the size of the Map
object is updated when:
Map
Map
Map.clear()
method to remove all elements from the Map
const map = new Map(); console.log(map.size); // ๐๏ธ 0 // โ add elements to the map map.set('name', 'bobby'); map.set('age', 30); console.log(map.size); // ๐๏ธ 2 // โ delete an element from the map map.delete('age'); console.log(map.size); // ๐๏ธ 1 // โ clear the map object map.clear(); console.log(map.size); // ๐๏ธ 0
We used the
Map.set()
method to add 2 elements to the Map
object.
Accessing the size
property on the Map
returns 2
at this point.
We used the
Map.delete()
method to remove an element from the Map
.
Accessing the size
property returned 1
after removing the element.
Finally, we used the
Map.clear()
method to remove all elements from the Map
, so the size
property returned
0
.
You can also use the Map.forEach()
method to get the length of a Map.
const map = new Map(); map.set('name', 'bobby'); map.set('age', 30); let length = 0; map.forEach((_value, _key) => { length += 1; }); console.log(length); // ๐๏ธ 2
We declared a length
variable and initialized it to 0
.
The Map.forEach()
method gets called for each key-value pair of the Map
.
On each iteration, we increment the length
by 1
.
Notice that we declared the length
variable using let
.
This is necessary because variables declared using const
cannot be reassigned.
Iterating over a Map
to calculate the length is an option, however, it isn't
necessary most of the time because the size
property is more convenient and
gets updated automatically.
You can learn more about the related topics by checking out the following tutorials: