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,
- Create a new Map object
map
with initial key-value pairs. - Use the
size
property to get the number of key/value pairs in themap
. - 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,
- Create a new Map object
map
with initial key-value pairs. - Use the
set()
method to add a new key-value pair to themap
. - Use the
size
property to get the updated number of key/value pairs in themap
. - 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,
- Create a new Map object
map
with initial key-value pairs. - Use the
delete()
method to remove a key-value pair from themap
. - Use the
size
property to get the updated number of key/value pairs in themap
. - 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.