How to Iterate over Set in Javascript


Set, a Javascript data structure, is a collection of unique values, providing a powerful tool for scenarios where distinct elements matter. But how do you iterate on a Javascript Set?

In this blogpost, you will explore code samples to iterate set in Javascript, common errors, and a fun coding problem to polish your skills.


Iteration Methods

Method 1: Using forEach() to iterate JS set

The forEach() method executes a provided function once for each element in the Set.

  • Pro: Concise
  • Con: Cannot break out of the loop, in between.
JavaScript
const mySet = new Set([1, 2, 3, 4]);

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

Method 2: Using for...of Loop

Classic for loop over Set elements:

JavaScript
const mySet = new Set(['apple', 'orange', 'banana']);

for (const element of mySet) {
    console.log(element);
}

Method 3: Using Spread Operator

The spread operator allows you to convert a Set to an array, enabling array methods for iteration.

JavaScript
const mySet = new Set([1, 2, 3]);
const setArray = [...mySet];

setArray.forEach(element => {
    console.log(element);
});

Method 4: Using Array.from()

The Array.from() method creates a new, shallow-copied array from an iterable object like a Set.

JavaScript
const mySet = new Set([10, 20, 30]);
const setArray = Array.from(mySet);

setArray.forEach(element => {
    console.log(element);
});

Method 5: Iterating with Set Entries

The entries() method returns an iterable of Set entries, allowing you to destructure key-value pairs.

JavaScript
const mySet = new Set(['red', 'green', 'blue']);

for (const [index, color] of mySet.entries()) {
    console.log(`Color at index ${index}: ${color}`);
}

Common Errors:

Undefined Set

If the Set is not initialized (undefined), using forEach() will result in an error. Ensure proper initialization.

JavaScript
let mySet; // Set not initialized

try {
    mySet.forEach(element => {
        console.log(element);
    });
} catch (error) {
    console.error("Error:", error.message);
}

Function Constraints

Unlike other loops, the break statement is not available in functions passed to Set.forEach(). Be cautious with control flow statements.

JavaScript
const mySet = new Set([10, 20, 30]);

// Error: The 'break' statement is not available in the function passed to Set.forEach()
mySet.forEach(element => {
    if (element === 20) {
        break;
        // ⚠ SyntaxError: Illegal break statement
    }
    console.log(element);
});

🧪Practice Coding Problem: Set Explorer

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Write a function setExplorer(set) that takes a Set and returns an array containing the square of each element in the Set.

JavaScript
/**
 * Explore the elements of a Set and return an array with the square of each element.
 * 
 * @param {Set} set - The Set to explore.
 * @returns {Array} - An array containing the square of each element.
 */
function setExplorer(set) {
  // > > > 👉 Write code here 👈 < < <
}

// Driver code
const myNumberSet = new Set([2, 4, 6, 8]);
console.log(setExplorer(myNumberSet)); 
// Expected Output: [4, 16, 36, 64]
Please attempt before seeing the Answer:
JavaScript
function setExplorer(set) {
    // Using Array.from() to create an array 
    // and map to square each element
    return Array.from(set, element => element * element);
}

Explanation:

  • The setExplorer function uses Array.from() to convert the Set to an array.
  • The map function is then applied to square each element in the array.
  • The final result is an array containing the square of each element in the original Set.

May your Sets are always iterable now! 🚀

Scroll to Top