The Wayback Machine - https://web.archive.org/web/20241230155159/https://www.geeksforgeeks.org/javascript-set-has-method/
Open In App

JavaScript Set has() Method

Last Updated : 12 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Set.has() method in JavaScript is used to check whether an element with a specified value exists in a Set or not. It returns a boolean value indicating the presence or absence of an element with a specified value in a Set.

Syntax:

mySet.has(value);

Parameters:

  • value: It is the value of the element that has to be checked if it exists in the Set.

Example 1: In this example, we have used sethas() method.

JavaScript
// Create a new set using Set() constructor
let myset = new Set();

// Append new elements to the 
// set using add() method
myset.add(23);
myset.add(12);

// As 23 exists 23, it will return true
console.log(myset.has(23));

Output
true

Example 2: In this example, we have used sethas() method.

JavaScript
// Create a new set using Set() constructor
let myset = new Set();

// Append new elements to the
// set using add() method
myset.add("Chicago");
myset.add("California");
myset.add("London");

// As London exists in the set,  
// it will return true
console.log(myset.has("London"));

// As Manchester does not exist in the 
// set, it will return false
console.log(myset.has("Manchester"));

Output
true
false

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

JavaScript Set has() Method- FAQs

What does the has() method do?

The has() method checks whether a specified value exists in a Set object. It returns a boolean value: true if the value is present, and false if it is not.

Is the has() method case-sensitive?

Yes, the has() method is case-sensitive. For example, checking for “apple” and “Apple” would be considered different values.

Can has() be used to check for the presence of complex objects?

Yes, but Set uses the SameValueZero algorithm to determine equality. This means that objects are compared by reference, not by content. Two different object instances with the same content are considered different.

Can has() be used on a Set with NaN values?

Yes, Set considers NaN equal to NaN, so if a Set contains NaN, the has() method will return true when checking for NaN

What is the most common use of the Set.prototype.has() method?

  • Checking for the Presence of Values: Determining if a specific value exists in a set, useful for operations like avoiding duplicates, validating membership, and performing set operations.

We have a complete list of Javascript Set methods, to check those please go through this Sets in JavaScript article.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.  


Next Article

Similar Reads

three90RightbarBannerImg