What is Map.has() method in Typescript?

Overview

Maps are helpful when we want to store key-value pair values. Maps are also known as dictionaries. It is one of the data structures available in many programming languages. The has() method is used to check if a particular key exists in a map.

Syntax

Map.has(key)
The has() method of a Map in TypeScript

Parameters

key: This represents the key whose existence we want to check.

Return value

This method returns a Boolean value. If the key exists, a true is returned. Otherwise, false is returned.

Code example

Let's look at the code below:

// 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.has("two")) // true
console.log(cart.has("bag")) // true
console.log(countries.has("GH")) // false
console.log(isMarried.has("Doe")) // true
console.log(evenNumbers.has(null)) // false

Code explanation

  • Lines 2 to 6: We create some maps.
  • Lines 9 to 13:  We use the has() method to check if the maps contain the specified keys. And we print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources