What is the map.clear() method in TypeScript?

Overview

The clear() method of a map in TypeScript clears all its key-value entries.

Syntax

Map.clear()
The clear() method of a map in TypeScript

Parameters

  • map: This is the map on which we apply the clear() function to clear its key-value pairs.

Return value

This method returns an empty map.

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>()
// Log out the maps before clearing their entries
console.log("Maps before clearing their entries")
console.log(evenNumbers)
console.log(cart)
console.log(countries)
console.log(isMarried)
console.log(emptyMap)
// Clear the maps
evenNumbers.clear()
cart.clear()
countries.clear()
isMarried.clear()
emptyMap.clear()
// Log out the maps after clearing their entries
console.log("\nMaps after clearing their entries")
console.log(evenNumbers)
console.log(cart)
console.log(countries)
console.log(isMarried)
console.log(emptyMap)

Explanation

  • Lines 2–6: We create some maps.
  • Lines 10–14: We log the maps we created before clearing their entries.
  • Lines 17–21: We clear the entries of the maps using the clear() method.
  • Lines 25–29: We log the empty maps onto the console.

    Free Resources