Javascript Set.has()
minoblue

minoblue @mino

Joined:
Aug 16, 2020

Javascript Set.has()

Publish Date: May 19
0 0

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 Set is implemented using a hash table under the hood (similar to Map).
  • When you use set.has(value), it:
  1. Computes a hash of the value.
  2. Uses this hash to look up the value in the underlying hash table.
  3. Checks for value equality using the SameValueZero algorithm (=== but treating NaN as equal to NaN).

Complexity:

  • Average case: O(1)
  • Worst case: O(n) — if there are many hash collisions (very rare in practice)

Notes:

  • Set only 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
Enter fullscreen mode Exit fullscreen mode

Let me know if you want a deeper look at how hashing or SameValueZero works.

Comments 0 total

    Add comment