A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type.
Sets have built-in methods designed for managing unique collections.
| Method | Description |
|---|---|
new Set() |
Creates a new Set |
add() |
Adds a new element to the Set |
delete() |
Removes an element from the Set |
has() |
Returns true if a value exists in the Set |
clear() |
Removes all elements from the Set |
forEach() |
Invokes a callback for each element |
You can create a Set by passing an array to the new Set() constructor, or by
adding values later using add().
// Method 1: Literal from array
const letters = new Set(["a", "b", "c"]);
// Method 2: Adding manually
letters.add("d");
letters.add("e");
letters.add("a"); // This will be ignored (already exists)
The has() method is much faster than searching through an array. This makes Sets
ideal for large collections where you frequently need to check for existence.
const colors = new Set(["Red", "Green", "Blue"]);
console.log(colors.has("Green")); // true
console.log(colors.has("Yellow")); // false
Similar to length for arrays, Sets have a size property that tells
you how many unique items are stored inside.
console.log(colors.size); // 3
let unique = [...new Set(myArray)];
add() is used to insert itemshas() is highly efficient for existence checkssize property to count elementsfor...of and
forEach()