Member-only story
Working with unique values is a common task in programming. JavaScript has a built-in Set object that makes managing unique values simple. In this post, we’ll explore using JavaScript Sets for unique value use cases.
Creating Sets
A Set can be initialized with any iterable object, like an array. Duplicates are automatically removed:
const ids = new Set([1, 2, 2, 3]);
// ids = Set(3) {1, 2, 3}
We can add additional values using .add():
ids.add(4);
// ids = Set(4) {1, 2, 3, 4}
And check for existence with .has():
ids.has(2);
// true
Removing Values
We can remove a value with .delete(), returning a boolean indicating whether the value existed:
ids.delete(3);
// true
ids.has(3);
// false
And clear out all values with .clear():
ids.clear();
// []
Iterating Sets
We can iterate over a set, such as to operate on each id:
for (let id of ids) {
console.log(id);
}