Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

set
javascript
has
communitycreator

What is the set.has() method in JavaScript?

Harris Amjad

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 JavaScript, the set.has() function is used to check if a set contains a specific element sent as a parameter.

Note: set.has() returns true if the set contains that element. Otherwise, it returns false.

The figure below shows a visual representation of the set.has() function:

Visual representation of the set.has() function

In JavaScript, a set is a particular instance of a list in which all inputs are unique.


Note: If there are duplicates, the set will only keep the first instance. For example: {'Tom','Alsvin','Eddie','Tom'} will result in {'Tom','Alsvin','Eddie'}.

Syntax

bool set_name.has(element)
// where the set_name is the name of the set.

Parameter

This function requires an element as a parameter.

Return value

This function returns a Boolean value, which is true if a specific element is present in a set and false if it isn’t.

Example

const set_1 = new Set(["Tom","Alsvin", "Eddie"]);
//elements in set
console.log("set_1 elements: ",set_1);
//set containing specific element
console.log("Eddie is present in the set: ", set_1.has("Eddie"));
//set not containing specific element
console.log("Jack is present in the set: ", set_1.has("Jack"));

Explanation

  • Line 1: We create a set with three values {'Tom','Alsvin','Eddie'} and name it set_1.

  • Line 7: We use set.has() to check if element Eddie is present in the set.

  • Line 10: We use set.has() to check if element Jack is present in the set.

RELATED TAGS

set
javascript
has
communitycreator

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