Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
typescript

What is set.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

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.

Syntax

set.has(value)
Syntax for the has() method of a Set in Typescript

Parameters

  • 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.

Return value

If the set contains the specified value, then a true is returned. Otherwise, false is returned.

Code example

Let's look at the code below:

// create some sets
let 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 values
console.log(names.has("Theodore")) // true
console.log(evenNumbers.has(5)) // false
console.log(booleanValues.has(true)) // true
console.log(countries.has("Tokyo")) // false
Using the has() method in TypeScript

Code explanation

  • Lines 2 to 5: We create some sets in TypeScript.
  • Lines 9 to 12: We use the has() method to check if some entries are contained in the sets we created. Then we print the results to the console.

RELATED TAGS

set
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