Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

What is Map.has() method in Typescript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
Using the has() method of a Map in TypeScript

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.

RELATED TAGS

typescript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring