.has()

The method checks for the presence of a value in a Set collection.

Time to read: less than 5 min

Briefly

The has() method checks whether a value exists in a Set. If the value is in the collection, the method returns true; otherwise, it returns false.

Example

        
          
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])console.log(watchList.has('Casino'))// trueconsole.log(watchList.has('Black Panther'))// false
          const watchList = new Set(['The Shining', 'Interstellar', 'Casino'])

console.log(watchList.has('Casino'))
// true

console.log(watchList.has('Black Panther'))
// false

        
        
          
        
      

How to Write

The method takes one argument - the value to check.

Returns a boolean value:

  • true if the collection contains the sought value;
  • false if the value is not in the collection.

In practice

Advice 1

🛠 You need to be careful when working with objects. Objects are stored and compared by reference, so the result of such code may surprise you:

        
          
          const users = new Set([  {name: 'Ivan', lastName: 'Petrov'},  {name: 'Petr', lastName: 'Ivanov'}])console.log(users.has({name: 'Ivan', lastName: 'Petrov'}))// false 🤷‍♂️
          const users = new Set([
  {name: 'Ivan', lastName: 'Petrov'},
  {name: 'Petr', lastName: 'Ivanov'}
])

console.log(users.has({name: 'Ivan', lastName: 'Petrov'}))
// false 🤷‍♂️

        
        
          
        
      

The thing is, two Ivans Petrov are actually different Ivans Petrov. This is easy to notice if you pay attention to the curly braces. Each pair of curly braces creates a new independent object, even though they look the same.

If you compare them with each other, the comparison result will also be false:

        
          
          console.log({name: 'Ivan', lastName: 'Petrov'} === {name: 'Ivan', lastName: 'Petrov'})// false
          console.log({name: 'Ivan', lastName: 'Petrov'} === {name: 'Ivan', lastName: 'Petrov'})
// false

        
        
          
        
      

The check will work correctly if we look for the same object:

        
          
          const petrov = {name: 'Ivan', lastName: 'Petrov'}const ivanov = {name: 'Petr', lastName: 'Ivanov'}const users = new Set([petrov, ivanov])console.log(users.has(petrov))// true
          const petrov = {name: 'Ivan', lastName: 'Petrov'}
const ivanov = {name: 'Petr', lastName: 'Ivanov'}
const users = new Set([petrov, ivanov])

console.log(users.has(petrov))
// true

        
        
          
        
      

🛠 If you need to add a value to a Set, you don't need to check if the value is already in the collection. Call add(). If the element is already in the collection, the addition will be ignored. Similarly with delete().