Sometimes, we want to iterate over set elements with JavaScript.
In this article, we’ll look at how to iterate over set elements with JavaScript.
How to iterate over set elements with JavaScript?
To iterate over set elements with JavaScript, we can use the for-of loop.
For instance, we write
const a = new Set();
a.add("Hello");
for (const key of a) {
console.log(key);
}
to create a set with the Set
constructor.
We add an entry into it with add
.
Then we use a for-of loop to loop through the entries of a
.
We get the entry being looped through from key
.
Conclusion
To iterate over set elements with JavaScript, we can use the for-of loop.