In TypeScript, we can use the has()
method of a set to check if the set contains the specified entry. Sets are used to store unique values that have no duplicates.
set.has(value)
set
: This is the set we want to check if it contains the specified value.value
: This is the value that we want to check if it exists.If the set contains the specified value, then a true
is returned. Otherwise, false
is returned.
Let's look at the code below:
// create some setslet names = new Set<string>(["Theodore", "David", "John", "Janme"])let evenNumbers = new Set<number>([2, 4, 6, 8, 10, 12])let booleanValues = new Set<boolean>([true, false])let countries = new Set<string>(["Nigeria", "Brazil", "Ghana", "Egypt", "Germany"])// check if they contain some valuesconsole.log(names.has("Theodore")) // trueconsole.log(evenNumbers.has(5)) // falseconsole.log(booleanValues.has(true)) // trueconsole.log(countries.has("Tokyo")) // false
has()
method to check if some entries are contained in the sets we created. Then we print the results to the console.