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.
Map.has(key)
key
: This represents the key whose existence we want to check.
This method returns a Boolean value. If the key exists, a true
is returned. Otherwise, false
is returned.
Let's look at the code below:
// create some Mapslet 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 entriesconsole.log(evenNumbers.has("two")) // trueconsole.log(cart.has("bag")) // trueconsole.log(countries.has("GH")) // falseconsole.log(isMarried.has("Doe")) // trueconsole.log(evenNumbers.has(null)) // false
has()
method to check if the maps contain the specified keys. And we print the results to the console.