JavaScript Set has()
Syntax & Examples

Set.has() method

The has() method of the Set object in JavaScript returns a boolean asserting whether an element with the given value is present in the Set object or not.


Syntax of Set.has()

The syntax of Set.has() method is:

has(value)

This has() method of Set returns a boolean asserting whether an element is present with the given value in the Set object or not.

Parameters

ParameterOptional/RequiredDescription
valuerequiredThe value of the element to test for presence in the Set.

Return Type

Set.has() returns value of type boolean.



✐ Examples

1 Using has() to check for a value in a Set

In JavaScript, we can use the has() method to check if a specific value is present in a Set object.

For example,

  1. Create a new Set object letters with initial values 'a', 'b', and 'c'.
  2. Use the has() method to check if the value 'b' is present in the letters Set.
  3. Log the result to the console using console.log().

JavaScript Program

const letters = new Set(['a', 'b', 'c']);
const hasB = letters.has('b');
console.log(hasB);

Output

true

2 Using has() to check for a non-existent value

In JavaScript, we can use the has() method to check if a value that is not present in the Set object returns false.

For example,

  1. Create a new Set object numbers with initial values 1, 2, and 3.
  2. Use the has() method to check if the value 4 is present in the numbers Set.
  3. Log the result to the console using console.log().

JavaScript Program

const numbers = new Set([1, 2, 3]);
const hasFour = numbers.has(4);
console.log(hasFour);

Output

false

3 Using has() with a Set of objects

In JavaScript, we can use the has() method to check if an object is present in a Set object.

For example,

  1. Create a new Set object people with initial objects representing different people.
  2. Use the has() method to check if a specific person object is present in the people Set.
  3. Log the result to the console using console.log().

JavaScript Program

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
const hasJohn = people.has(person1);
console.log(hasJohn);

Output

true

Summary

In this JavaScript tutorial, we learned about has() method of Set: the syntax and few working examples with output and detailed explanation for each example.