1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How to Iterate over Set in Javascript

ReadTime: 4 minutes

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);
});
Using forEach() to iterate JS set

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);
}
Using for...of loop to iterate Set elements

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);
});
Using Spread operator convert Set to an array

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);
});
Loop using Array.from() over JavaScript array

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}`);
}
Iterating with set entries

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);
}
Possibility of error on undefined set

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);
});
Problem Code

πŸ§ͺ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.

Problem (JavaScript)

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]
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
function setExplorer(set) {
  // Using Array.from() to create an array
  // and map to square each element
  return Array.from(set, element => element * element);
}
Solution Code

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! πŸš€

Contact

Feel free to reach out!