The JavaScript Set.prototype.has() method uses hashing to perform searches, which enables it to check for the presence of an element in constant time (O(1)) in most cases.
How it works internally:
- JavaScript
Setis implemented using a hash table under the hood (similar toMap). - When you use
set.has(value), it:
- Computes a hash of the value.
- Uses this hash to look up the value in the underlying hash table.
- Checks for value equality using the SameValueZero algorithm (
===but treatingNaNas equal toNaN).
Complexity:
- Average case: O(1)
- Worst case: O(n) — if there are many hash collisions (very rare in practice)
Notes:
-
Setonly stores unique values. - Works for both primitive types and objects, but for objects, identity matters:
const set = new Set();
set.add({ a: 1 });
set.has({ a: 1 }); // false — different object reference
Top comments (0)