JavaScript Sets
A Set is a special type collection β βset of valuesβ (without keys), where each value may occur only once. Introduced in ES6, it provides high-performance value checking compared to standard Arrays.
Sets vs Arrays
While Arrays use indexes (0, 1, 2) to store and retrieve data, Sets operate without an index. The main feature of a Set is its uniqueness constraint: you cannot add the exact same value twice. If you attempt to add an existing value, the Set ignores it quietly.
Key Properties & Methods
- .add(value) β Appends value to the set, returns the set itself.
- .has(value) β Returns true if the value exists in the set, otherwise false.
- .delete(value) β Removes the value. Returns true if value existed.
- .clear() β Removes everything from the set.
- .size β Returns the current element count. Note: it is NOT
length.
The Classic Use Case: Deduplication
The most common use case for a Set in everyday JavaScript is filtering an array to remove duplicate elements. Because the Set constructor accepts an iterable, and the spread operator translates iterables back into arrays, deduplication is a clean one-liner:
const rawData = ['apple', 'banana', 'apple', 'orange']; const uniqueData = [...new Set(rawData)]; // uniqueData is ['apple', 'banana', 'orange']
View WeakSet Details+
In JavaScript, there is also a data structure called WeakSet. A WeakSet behaves similarly to a Set, but it only accepts objects as values, and references to those objects are held "weakly". This means that if there are no other references to an object stored in the WeakSet, it can be garbage collected. This makes WeakSets great for tracking objects without causing memory leaks, although they cannot be iterated over.
