What is map.set() in TypeScript?

Overview

A map is made up of key-value pairs. Sometimes, it is referred to as a dictionary.

We can use the set() method of Map in TypeScript to add entries to a map. To add entries, we simply provide the key-value pair we want to add.

Syntax

Map.set(key, value)
Syntax for adding an entry to a map in TypeScript

Note: Map will be replaced with the name of the name of the Map object we use.

Parameters

  • key, value: This is the pair we want to add to the map, since a map is made up of key-value pairs. These can be of any data type.

Return value

This method returns a new map with the key-value pair inserted into it.

Example

Let's look at an example of maps.

// Create some maps
let evenNumbers = new Map<string, number>([["two", 2], ["four", 4], ["eight", 8]])
let cart = new Map<string, number>([["rice", 500], ["bag", 10]])
let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])
let isMarried = new Map<string, boolean>([["James", false], ["Jane", true], ["Doe", false]])
let emptyMap = new Map<null, null>()
// Add entries using the set method
evenNumbers.set("twenty", 20)
cart.set("vodka", 50)
countries.set("IR", "Iran")
isMarried.set("Emeka", true)
emptyMap.set(null, null)
// Print out the maps
console.log(evenNumbers)
console.log(cart)
console.log(countries)
console.log(isMarried)
console.log(emptyMap)

Explanation

  • Lines 2–6: We create some maps.
  • Lines 9–13: We use the set() method to add some entries to the maps we created.
  • Lines 16–20: We print out the maps to the console.

Free Resources