Course contentsShow
← JavaScript
Lesson 1047 of 2,72324. Maps and SetsFree lesson

Checking Membership with has()

Test whether a value exists in a Set using the has() method for O(1) lookup.

Checking Membership with has()

You'll learn how to quickly check if a value exists in a Set using the blazingly fast has() method.

What is has()?

The has() method is your go-to tool for testing whether a specific value exists in a Set. Think of it like asking a bouncer "Is this person on the guest list?" — you get an instant yes or no answer.

Unlike arrays where you'd use includes() and JavaScript might scan through every element (slow!), Sets use an optimized internal structure that checks membership in constant time — O(1) in computer science terms. This means checking takes roughly the same amount of time whether your Set has 10 items or 10,000 items.

How It Works

Call has() on your Set and pass the value you're looking for. You'll get true if it's there, false if it's not:

const fruits = new Set(['apple', 'banana', 'orange']);

console.log(fruits.has('apple'));    // true
console.log(fruits.has('grape'));    // false
console.log(fruits.has('APPLE'));    // false (case-sensitive)

Remember: Identity Matters

Like all Set operations, has() uses the same equality check as ===. This means objects are compared by reference, not by content:

const items = new Set();
const obj = { id: 1 };

items.add(obj);

console.log(items.has(obj));         // true (same reference)
console.log(items.has({ id: 1 }));   // false (different object)

Key Takeaway: Use has() for instant membership checks in Sets — it's fast, readable, and one of the main reasons to choose Sets over arrays for membership testing.