The Set object provides a powerful way to work with unique values in JavaScript, unlocking simpler handling of distinctive items compared to hacky workarounds.
In this article we’ll break down how to use JavaScript Sets for improved collection code across your apps.
Motivating JavaScript Sets
Consider tracking tag selections — we want unique additions only:
let tags = [];
function addTag(tag) {
if (!tags.includes(tag)) {
tags.push(tag);
}
}
This ensures no duplicate tag inserts. Now compare with a Set:
const tags = new Set();
function addTag(tag) {
tags.add(tag);
}
The Set automatically handles uniqueness — no extra logic needed!
Set Fundamentals
Sets contain only distinct values of any type. Core characteristics:
- Unique value storage
- Efficient lookup Big O(1)
- Insertion order iteration
We can initialize Sets with data:
const ids = new Set([1, 2, 2, 3, 4]); // {1, 2, 3, 4}
const roles = new Set('developer')…