What is the values() method of a Map in TypeScript?

Overview

We can use a Map to store the data with key-value pairs as well as dictionary data. Using the values() method, we get all the values of every key present in the dictionary. It returns these values as an iterator.

Syntax

Map.values()
The values() method of a Map in TypeScript

Parameters

Map: This is the map whose values we want to get.

Return value

It returns an iterator of the Map type containing its values.

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 iterators
let itr1 = oddNumbers.values()
let itr2 = products.values()
let itr3 = countries.values()
let itr4 = isOld.values()
let itr5 = nullishMap.values()
// log out the iterators
console.log(itr1)
console.log(itr2)
console.log(itr3)
console.log(itr4)
console.log(itr5)
// log out values for any of the iterators
for (let value of itr1) {
console.log(value);
}

Explanation

  • Lines 2–6: We create some maps in TypeScript and initialize them with some data.
  • Lines 9–13: We use the values() method to get the iterators of the created sets.
  • Lines 16–20: We use console.log() to log the Map iterators to the console.
  • Lines 23: We use the for of loop to iterate over one of the iterators. Next, we print its values to the console screen.