How to use a Set in JavaScript
JavaScript Set objects provide an efficient way to store unique values and perform collection operations without duplicates.
As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve used Sets extensively for managing unique collections in UI components and data processing.
From my expertise, the most effective approach is creating Sets with the new Set() constructor and using their built-in methods for adding, checking, and iterating values.
Sets offer better performance than arrays for uniqueness checks and provide cleaner syntax for collection operations.
Create a Set using new Set() constructor to store unique values and perform efficient collection operations.
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4])
console.log(uniqueNumbers) // Set(4) { 1, 2, 3, 4 }
Here new Set([1, 2, 2, 3, 3, 4]) creates a Set from an array, automatically removing duplicate values. Sets maintain insertion order and provide methods like add(), has(), delete(), and clear(). The size property returns the number of unique values. Sets are iterable, so you can use for...of loops, forEach(), or convert them back to arrays using spread syntax [...uniqueNumbers].
Best Practice Note:
This is the same approach we use in CoreUI components for managing unique CSS classes, avoiding duplicate event listeners, and filtering unique data values. Sets provide O(1) performance for checking if a value exists, making them ideal for large collections where uniqueness matters.



