What is Map.size in TypeScript?

Overview

Map.size is a property of a map in TypeScript. It is used to find out the total number of entries in a map. It returns an integer value.

Syntax

Map.size
Syntax for size property of a Map in TypeScript

Parameters

Map: This is the map whose total size we want to know.

Return value

The value returned is an integer that is the number of elements the map contains.

Code example

// Create some maps
let oddNumbers = new Map<string, number>([["one", 1], ["three", 3], ["five", 5]])
let products = new Map<string, number>([["rice", 500], ["bag", 10]])
let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])
let isOld = new Map<string, boolean>([["James", false], ["Jane", true], ["Doe", false]])
let nullishMap = new Map<null, null>()
// get the sizes
console.log(oddNumbers.size)
console.log(products.size)
console.log(countries.size)
console.log(isOld.size)
console.log(nullishMap.size)

Explanation

  • Lines 2–6: We create some maps in TypeScript and initialize them with some values.
  • Lines 9–13: With the size property, we get the size of each map and print the value to the console.

Free Resources