JavaScript – Iterate over Elements of a Set
To iterate over elements of a Set in JavaScript, call values() method on this set which returns an iterator and use for-of loop over this iterator.
Refer JavaScript For-of Loop.
Syntax
The syntax to get iterator for elements in the Set set1
using values() method is
set1.values()
We may use for-of loop as shown in the following to iterate over the elements of this iterator.
for (element of set1.values()) { //code }
ADVERTISEMENT
Examples
In the following example, we take a Set with initialised with three element. We shall check if the element 'banana'
is present in this Set using has() method.
index.html
Conclusion
In this JavaScript Tutorial, we learned how to iterate over the elements of this Set in JavaScript using values() method and for-of loop, with examples.