Menu
Coddy logo textTech

Iterating Over Sets

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 29 of 65.

Sets in JavaScript are iterable, which means you can loop through their elements. There are several ways to iterate over a Set:

  1. Using the for...of loop:
const mySet = new Set([1, 2, 3, 4, 5]);
for (const item of mySet) {
  console.log(item);
}
  1. Using the forEach method:
mySet.forEach(item => {
  console.log(item);
});
  1. Converting to an array and using array methods:
const myArray = Array.from(mySet);
myArray.forEach(item => {
  console.log(item);
});

Each of these methods will iterate over the Set in the order of insertion.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

Cheat sheet

Sets in JavaScript are iterable and can be looped through in several ways:

Using for...of loop:

const mySet = new Set([1, 2, 3, 4, 5]);
for (const item of mySet) {
  console.log(item);
}

Using forEach method:

mySet.forEach(item => {
  console.log(item);
});

Converting to array and using array methods:

const myArray = Array.from(mySet);
myArray.forEach(item => {
  console.log(item);
});

All methods iterate over the Set in the order of insertion.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow