For Of Loop


The for...of loop, introduced in ES6, provides a modern and straightforward way to iterate over iterable objects in JavaScript. This includes built-in types like Array, String, Map, and Set, making your code more readable and concise compared to a traditional for loop. It directly accesses the value of each element in the collection for each iteration.


Example 1: Iterating over an Array

// Define an array of numbers.
const numbers = [10, 20, 30, 40, 50];

// Loop through each number in the array.
for (const number of numbers) {
  // Log the current number to the console.
  console.log(number);
}
// Expected Output:
// 10
// 20
// 30
// 40
// 50

Explanation

This code demonstrates the most common use of the for...of loop to iterate through an array. In each iteration, the number variable is assigned the value of the current element from the numbers array, which is then printed to the console.


Example 2: Iterating over a String

JavaScript

 

// Define a string variable.
const greeting = "Hello";

// Loop through each character of the string.
for (const char of greeting) {
  // Log the current character to the console.
  console.log(char);
}
// Expected Output:
// H
// e
// l
// l
// o

Explanation

Strings in JavaScript are iterable objects, allowing the for...of loop to access each character one by one. The char variable holds the character for the current iteration, making it simple to perform operations on individual characters of a string.


Example 3: Iterating over a Map

// Create a new Map object.
const userRoles = new Map();

// Set key-value pairs for the map.
userRoles.set('admin', 'Alice');
userRoles.set('editor', 'Bob');

// Loop through the map's entries.
for (const [role, user] of userRoles) {
  // Log the role and user to the console.
  console.log(`${user} is an ${role}.`);
}
// Expected Output:
// Alice is an admin.
// Bob is an editor.

Explanation

When used with a Map, the for...of loop iterates over its [key, value] pairs. We use array destructuring [role, user] to conveniently assign the key and value to separate variables in each iteration.


Example 4: Iterating over a Set

// Create a new Set with unique values.
const uniqueIds = new Set([101, 102, 101, 103]);

// Loop through each value in the Set.
for (const id of uniqueIds) {
  // Log the current id to the console.
  console.log(id);
}
// Expected Output:
// 101
// 102
// 103

Explanation

A Set is a collection of unique values, and the for...of loop iterates through these unique elements in their insertion order. The loop automatically handles the uniqueness of Set elements, as seen with the duplicate 101 being ignored.


Example 5: Iterating over Function Arguments

// Define a function that sums all its arguments.
function sumAll() {
  let total = 0;
  // The 'arguments' object is an array-like iterable.
  for (const value of arguments) {
    total += value;
  }
  return total;
}

// Call the function with multiple arguments.
console.log(sumAll(5, 10, 15)); // Expected Output: 30

Explanation

Inside a function, the arguments object is an array-like iterable that contains all arguments passed to it. The for...of loop can iterate directly over this object to access each argument, making the function flexible and able to handle a variable number of inputs.


Example 6: Iterating over a NodeList

// Assume this HTML:
// <p>First paragraph.</p>
// <p>Second paragraph.</p>

// Select all paragraph elements, which returns a NodeList.
const paragraphs = document.querySelectorAll('p');

// Loop through each paragraph element in the NodeList.
for (const p of paragraphs) {
  // Add a CSS class to each paragraph.
  p.classList.add('highlight');
}

Explanation

The document.querySelectorAll() method returns a NodeList, which is an iterable collection of DOM elements. The for...of loop provides an effective way to iterate through this list to manipulate each DOM node, such as adding a CSS class.


Example 7: Iterating with break and continue

// An array of various numbers.
const dataPoints = [12, 5, 8, 130, 44, 9];

// Loop through the data points.
for (const point of dataPoints) {
  // Skip any numbers less than 10.
  if (point < 10) {
    continue;
  }
  // If a number is over 100, stop the loop.
  if (point > 100) {
    break;
  }
  // Log the valid data point.
  console.log(point);
}
// Expected Output:
// 12
// 44

Explanation

The for...of loop works with control flow statements like continue and break. In this example, continue skips the current iteration if a value is too small, and break exits the loop entirely if a value is too large.