JavaScript for...of Loop: Iterating Iterable Objects

The for...of loop in JavaScript is a powerful and concise way to iterate over iterable objects. Introduced in ECMAScript 6 (ES6), it offers a more straightforward approach compared to the traditional for loop or the forEach method, especially when dealing with collections like arrays, strings, maps, sets, and more. This guide will explore the syntax, functionality, and various use cases of the for...of loop, helping you effectively use it in your JavaScript projects.

What is an Iterable Object?

Before diving into the for...of loop, it’s essential to understand what constitutes an “iterable” object in JavaScript. An iterable is an object that has a method that returns an iterator. An iterator is an object that knows how to access the items from the collection one at a time and has a next() method that returns an object with value and done properties.

Common iterable objects in JavaScript include:

  • Arrays: Ordered collections of elements.
  • Strings: Sequences of characters.
  • Maps: Collections of key-value pairs, where keys can be of any type.
  • Sets: Collections of unique values.
  • NodeLists: Collections of DOM elements.
  • Arguments Objects: Objects containing arguments passed to a function.

The for...of loop is specifically designed to work with these iterable objects, providing an easy way to access their individual elements.

Purpose of the for...of Loop

The primary purpose of the for...of loop is to:

  • Simplify Iteration: Provide a cleaner, more readable syntax for iterating over iterable objects.
  • Access Values Directly: Directly access the values of iterable objects without needing to manage indices or keys.
  • Enhance Readability: Improve code clarity compared to traditional for loops when working with collections.
  • Iterate Various Data Structures: Seamlessly iterate over arrays, strings, maps, sets, and other iterable objects.

Syntax of the for...of Loop

The basic syntax of the for...of loop is as follows:

for (const variable of iterable) {
  // code to be executed for each element
}

Here:

  • variable: A variable declared with const (or let) that takes the value of each element from the iterable object during each iteration.
  • iterable: The iterable object (e.g., an array, string, map, set) that is to be iterated over.

Examples of the for...of Loop

Let’s explore the for...of loop with various iterable objects, starting with basic examples and then moving to more complex use cases.

Iterating Through an Array

The most common use case for the for...of loop is iterating through arrays. This provides a cleaner and more direct way to access the array elements compared to traditional for loops:

<div id="arrayOutput"></div>
<script>
    const array_example = ["apple", "banana", "cherry"];
    let array_output_string = "";
    for (const fruit of array_example) {
        array_output_string += fruit + ", ";
    }
    document.getElementById("arrayOutput").textContent = "Fruits: " + array_output_string.slice(0, -2); // Remove trailing comma and space
</script>

Output:

In this example, the for...of loop directly iterates through the array_example and assigns each fruit to the fruit variable.

Iterating Through a String

Strings in JavaScript are also iterable, allowing you to loop through individual characters using for...of.

<div id="stringOutput"></div>
<script>
    const string_example = "Hello";
    let string_output_string = "";
    for (const char of string_example) {
        string_output_string += char + " ";
    }
    document.getElementById("stringOutput").textContent = "Characters: " + string_output_string;
</script>

Output:

Here, the loop iterates over each character in the string_example.

Iterating Through a Map

Maps are collections of key-value pairs. When using the for...of loop with a Map, each iteration provides a pair of key-value as an array.

<div id="mapOutput"></div>
<script>
  const map_example = new Map([
    ["name", "John"],
    ["age", 30],
    ["city", "New York"],
  ]);
  let map_output_string = "";
  for (const [key, value] of map_example) {
    map_output_string += key + ": " + value + ", ";
  }
  document.getElementById("mapOutput").textContent = "Map: " + map_output_string.slice(0,-2);
</script>

Output:

In this case, we use array destructuring to directly extract key and value in the loop.

Iterating Through a Set

Sets are collections of unique values. The for...of loop iterates through each element in the set.

<div id="setOutput"></div>
<script>
  const set_example = new Set([1, 2, 3, 2, 1]);
    let set_output_string = "";
    for (const value of set_example) {
      set_output_string += value + ", ";
    }
    document.getElementById("setOutput").textContent = "Set: " + set_output_string.slice(0, -2);
</script>

Output:

The loop provides direct access to the unique values in the set.

Iterating Through a NodeList

NodeList objects, often returned by DOM methods like querySelectorAll, can be iterated using for...of.

<ul id="listItems">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<div id="nodeListOutput"></div>

<script>
  const nodeList_example = document.querySelectorAll("#listItems li");
  let nodeList_output_string = "";
  for (const item of nodeList_example) {
    nodeList_output_string += item.textContent + ", ";
  }
  document.getElementById("nodeListOutput").textContent = "List Items: " + nodeList_output_string.slice(0,-2);
</script>

Output:

  • Item 1
  • Item 2
  • Item 3

This allows you to iterate over each DOM element selected.

Key Differences between for...of and for...in

It’s important to distinguish the for...of loop from the for...in loop. While both are used for iteration, they operate on different principles:

| Feature | for...of Loop | for...in Loop |
|——————-|—————————————|——————————————-|
| Iteration | Iterates over values of iterable objects | Iterates over keys or properties of objects |
| Iterable Type | Designed for iterable objects | Designed for objects, including non-iterables|
| Use Case | Arrays, strings, maps, sets, etc. | Objects, including arrays (but not recommended for it) |
| Access | Accesses values directly | Accesses keys or property names |
| Order | Guaranteed order of iteration | Order not guaranteed for objects |

Note: The for...in loop is better suited for iterating over the properties of an object rather than the values of iterable objects. 💡

Practical Use Cases

Summing Array Elements

Using for...of for summing the elements of an array simplifies the operation:

<div id="sumOutput"></div>
<script>
  const numbers_example = [1, 2, 3, 4, 5];
    let sum = 0;
    for (const num of numbers_example) {
      sum += num;
    }
    document.getElementById("sumOutput").textContent = "Sum: " + sum;
</script>

Output:

Transforming Array Elements

Applying operations to each element becomes easy and clean:

<div id="transformOutput"></div>
<script>
    const nums_example = [1, 2, 3];
    const squared_example = [];
    for (const num of nums_example) {
        squared_example.push(num * num);
    }
    document.getElementById("transformOutput").textContent = "Squared: " + squared_example.join(", ");
</script>

Output:

Processing String Characters

Extracting or modifying characters in a string can be done efficiently:

<div id="stringProcessOutput"></div>
<script>
    const str_example = "JavaScript";
    let output_string_process = "";
    for (const char of str_example) {
      if(char.toLowerCase() !== 'a') {
          output_string_process += char;
      }
    }
    document.getElementById("stringProcessOutput").textContent = "Filtered String: " + output_string_process;
</script>

Output:

Browser Support

The for...of loop has excellent support in all modern browsers, ensuring consistent behavior across different platforms.

Browser Version
Chrome 38+
Firefox 13+
Safari 7.1+
Opera 25+
Edge 12+
Internet Explorer Not supported (use polyfills for older versions)

Note: The for...of loop is a modern feature, but if you need to support older browsers, you may need to use polyfills to add this functionality. ⚠️

Conclusion

The for...of loop is an essential part of modern JavaScript, offering a simplified and readable way to iterate over iterable objects. With its ease of use and broad application, it significantly enhances code clarity and efficiency when working with collections such as arrays, strings, maps, and sets. By mastering the for...of loop, you’ll be equipped to write more concise and maintainable JavaScript code.