In JavaScript, a Set is a built-in object that allows us to store unique values of any type, whether primitive values or object references.
Sets are similar to arrays, but they only allow unique values, which means no duplicate elements are allowed.
Here's a basic overview of how we can use Sets in JavaScript:
// Creating an empty Set let yourSet = new Set(); // Creating a Set with initial values let numberSet = new Set([1, 2, 3, 4, 5, 6, 7]); // We can also use the add method to add elements to a Set numberSet.add(8);
add(value): Adds a new element with the specified value to the Set.
// Creating an empty Set let yourSet = new Set(); yourSet.add("red"); yourSet.add("green"); yourSet.add("red"); // Duplicate values are ignored
yourSet.delete("green");
console.log(yourSet.has("red")); // true console.log(yourSet.has("green")); // false
console.log(yourSet.size); // 1
yourSet.clear();
delete(value): Removes the specified value from the Set.
has(value): Returns a boolean indicating whether the Set contains a specific value.
yourSet.forEach((value) => { console.log(value); }); // Or using a for...of loop for (let value of yourSet) { console.log(value); }
size: Returns the number of elements in the Set.
clear(): Removes all elements from the Set.
We can use the "forEach" method or the for...of loop to iterate over the elements of a Set.