Glossary / Set

Set

Set stores unique values in insertion order. It is useful for membership checks, deduplication, and set-like operations. Uniqueness is determined by SameValueZero rather than deep structural comparison: primitive values compare by value, while objects compare by reference identity.

Membership and order

const values = new Set([1, 1, NaN, NaN]);
[...values]; // [1, NaN]

const a = { id: 1 };
new Set([a, { id: 1 }]).size; // 2

Adding an existing value does not create another entry or move its position. Deleting then re-adding places it at the end. add returns the Set, so additions can be chained. The collection is iterable in insertion order and exposes a size, but it does not perform deep equality. To deduplicate records by a domain field, derive a stable key or implement an explicit comparator/index.

The spec requires average sublinear access, not exact O(1) performance. Set membership is often convenient, but construction and conversion have costs. JSON serialization does not preserve Set members automatically; convert to a deliberate array or another schema.

Interview questions

  1. How does Set treat NaN? All NaN entries are treated as one value.
  2. Does Set deep-deduplicate objects? No, object references are compared by identity.
  3. What does re-adding a deleted item do to its order? It appears at the end.
  4. How deduplicate by record ID? Use a key-based map/set or an explicit filter keyed by ID.

References