Iterating Over Sets
You'll learn how to loop through all the values in a Set using multiple iteration techniques.
The Core Idea
Once you have a Set filled with values, you'll often need to process each element. JavaScript provides several ways to iterate over Sets: the for...of loop, the forEach method, and direct use of the Set's iterator through values(), keys(), and entries() methods.
Using for...of
The most straightforward way to loop through a Set:
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
// Output: red, green, blue
Using forEach
Just like arrays, Sets have a forEach method:
const numbers = new Set([1, 2, 3]);
numbers.forEach((value) => {
console.log(value * 2);
});
// Output: 2, 4, 6
Note: forEach on Sets receives the same value twice (value, value, set) for consistency with Map's forEach, but you'll typically only use the first parameter.
Using Iterator Methods
You can explicitly call values(), keys() (same as values for Sets), or entries():
const fruits = new Set(['apple', 'banana']);
for (const fruit of fruits.values()) {
console.log(fruit); // apple, banana
}
for (const [value, valueCopy] of fruits.entries()) {
console.log(value); // value and valueCopy are identical
}
Key Takeaway: Sets can be iterated using for...of (most common), forEach, or iterator methods like values() and entries(), with iteration always occurring in insertion order.