What is the map.delete() method in Typescript?

Overview

A map, also known as a dictionary, is a data structure to store key-value pairs. It consists of keys with their corresponding values. With the delete() method, we can delete a key-pair entry by just specifying the key.

Syntax

Set.delete(key)
Syntax for the delete() method of a map in TypeScript

Parameters

  • key: This is the key whose value we want to delete.

Return value

This method returns a boolean value. If the key is found and the entry is deleted, it returns true. Otherwise, it returns false.

Example

// 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>()
// Delete some entries
console.log(evenNumbers.delete("two")) // true
console.log(cart.delete("bag")) // true
console.log(countries.delete("GH")) // false
console.log(isMarried.delete("Doe")) // true
console.log(evenNumbers.delete(null)) // false
// Log out modified 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: With the delete() method, we delete some entries by specifying their keys.
  • Lines 16–20: We print the modified maps to the console.

Free Resources