Skip to content

Instantly share code, notes, and snippets.

@DoctorDerek
Created November 2, 2020 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DoctorDerek/9b2c7821ec42d7945b3536d769783e3e to your computer and use it in GitHub Desktop.
Save DoctorDerek/9b2c7821ec42d7945b3536d769783e3e to your computer and use it in GitHub Desktop.
Three methods to iterate through a JavaScript ES6 Set object
const emojiSet = new Set(["🙋🏼", "🦾", "🦿", "🙋🏼"])
//  Use Set.prototype.keys() or Set.prototype.values()
const emojiIterator = emojiSet.values()
// You can use a for...of loop with an Iterator object
for (const emoji of emojiIterator) {
console.log(emoji)
}
// emojiSet.keys() is equivalent to: emojiSet.values()
for (const emoji of emojiSet.keys()) {
console.log(emoji)
}
// Output: "🙋🏼", "🦾", "🦿"
// Use Set.prototype.forEach() with a Callback Function
emojiSet.forEach((emoji) => {
console.log(emoji)
})
// Output: "🙋🏼", "🦾", "🦿"
//  Use a for...of Loop Directly With the New Set
for (const emoji of emojiSet) {
console.log(emoji)
}
// Output: "🙋🏼", "🦾", "🦿"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment