To get the size (number of key-value pairs) of a map in TypeScript, you can use the size property. This property returns the number of elements in the map.
We can get the size of a map in TypeScript using the size property, which provides the number of key-value pairs in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.size
property to get the number of key-value pairs in the map.mapSize
.console.log
function to verify the number of key-value pairs in the map.const myMap = new Map<string, number>([
['one', 1],
['two', 2],
['three', 3]
]);
// Get the size of the map
const mapSize = myMap.size;
// Print the size
console.log('Size of the map:', mapSize);
Size of the map: 3
We can also get the size of an empty map in TypeScript using the size property, which returns 0 when the map is empty.
For example,
emptyMap
with string keys and integer values.size
property to get the number of key-value pairs in the empty map.emptyMapSize
.console.log
function to verify that the map is empty.const emptyMap = new Map<string, number>();
// Get the size of the empty map
const emptyMapSize = emptyMap.size;
// Print the size
console.log('Size of the empty map:', emptyMapSize);
Size of the empty map: 0
We can get the size of a map in TypeScript after adding elements using the size property, which provides the updated number of key-value pairs in the map.
For example,
dynamicMap
with string keys and integer values.set
method.size
property to get the number of key-value pairs in the map after adding elements.dynamicMapSize
.console.log
function to verify the updated number of key-value pairs in the map.const dynamicMap = new Map<string, number>();
// Add elements to the map
dynamicMap.set('one', 1);
dynamicMap.set('two', 2);
dynamicMap.set('three', 3);
// Get the size of the map after adding elements
const dynamicMapSize = dynamicMap.size;
// Print the size
console.log('Size of the map after adding elements:', dynamicMapSize);
Size of the map after adding elements: 3
In this tutorial, we learned How to Get the Size (Number of Key-Value Pairs) of a Map in TypeScript language with well detailed examples.