Skip to content

Set

The Set object is a collection of unique values. Unlike arrays, each value can occur only once in a Set. Sets are useful for eliminating duplicates and for membership testing.

Arrays have limitations for certain use cases:

  • No built-in uniqueness enforcement
  • Checking existence requires iteration (O(n))
  • Removing duplicates is verbose
FeatureDescription
UniquenessEach value appears only once
Any valuesCan store primitives and objects
OrderMaintains insertion order
Size.size property for length check
PerformanceO(1) lookup time with has()
const set = new Set();
const setFromIterable = new Set([1, 2, 3, 3, 4]); // Creates Set {1,2,3,4}
  • Sets automatically remove duplicate values.
  • Values are compared using SameValueZero algorithm.
  • Insertion order is preserved.
  • NaN can be stored (only one NaN).
  • Sets are iterable by default.
// Creating Sets
const emptySet = new Set();
console.log(emptySet.size); // 0
// From array (duplicates removed)
const numberSet = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(numberSet); // Set {1, 2, 3, 4, 5}
console.log(numberSet.size); // 5
// From string
const charSet = new Set("hello");
console.log(charSet); // Set {'h', 'e', 'l', 'o'} (l appears only once)
// Mixed types (primitives)
const mixedSet = new Set([1, "1", true, "true"]);
console.log(mixedSet.size); // 4 (1 and '1' are different)
// Objects are unique by reference
const obj1 = { id: 1 };
const obj2 = { id: 1 };
const objSet = new Set([obj1, obj2, obj1]);
console.log(objSet.size); // 2 (obj1 and obj2 are different objects)
// NaN handling (only one NaN)
const nanSet = new Set([NaN, NaN, NaN]);
console.log(nanSet.size); // 1