Syntax
const mySet = new Set([values]);
mySet.add(value);
mySet.has(value);Examples
Basic Set Operations
Creating a Set and using its core methods.
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // ignored - 2 is already in the set
mySet.add(3);
console.log(mySet.size); // 3
console.log(mySet.has(2)); // true
mySet.delete(2);
console.log(mySet.has(2)); // falseDeduplicating an Array
One of the most common uses of Set - removing duplicates.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]Iterating a Set
Sets are iterable and work with for...of.
const tags = new Set(["js", "web", "css"]);
for (const tag of tags) {
console.log(tag);
}
// js, web, css - in insertion order
tags.forEach(tag => console.log(tag)); // also worksBest practices
- Use Set instead of an array when you need to guarantee uniqueness and do not need indexed access
- Use the [...new Set(array)] pattern as the concise standard way to deduplicate an array
- Remember Set uses the same equality as ===, with the one exception that NaN is treated as equal to itself
- Use has() for membership checks instead of array includes() - Set lookups are generally faster for large collections
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification