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:
- Using the
for...ofloop:
const mySet = new Set([1, 2, 3, 4, 5]);
for (const item of mySet) {
console.log(item);
}
- Using the
forEachmethod:
mySet.forEach(item => {
console.log(item);
});
- 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys