javascript for-of loop

JavaScript: for-of Loop

In JavaScript, the for-of loop is a powerful and versatile tool for iterating over iterable objects. Unlike the for-in loop, which iterates over the keys or indices of an object or array, the for-of loop allows you to directly access the values of iterable data structures such as arrays, strings, maps, and sets.

When you’re working with collections like arrays or strings, the for-of loop is an ideal choice. It provides a simple, readable way to access each element without needing to manually track the index or key. This makes it especially useful for handling various types of data structures and simplifies the iteration process.

The goal of this article is to guide you through the different ways you can use the for-of loop effectively. By the end, you’ll be comfortable iterating through arrays, strings, maps, and even custom iterable objects with ease. Let’s dive into how the for-of loop works and explore its versatility!

Basic Syntax of the for-of Loop

The for-of loop follows a simple and clean syntax:

for (let element of iterable) {
  // Code to execute
}

  • element: This is the variable that holds the current value in the iteration. It represents each item in the iterable data structure (like an array, string, or set) one by one as the loop runs.
  • iterable: This refers to the data structure you’re iterating over. It can be an array, string, map, set, or any other object that is iterable. The for-of loop will iterate through the values of this iterable, not the indices or keys.

For example, if you’re iterating over an array, element will hold each item in the array, one at a time. Similarly, when iterating over a string, element will hold each character.

const colors = ['red', 'green', 'blue'];

for (let color of colors) {
  console.log(color);
}
// Output: red, green, blue

Here, color is the element, and colors is the iterable (array) you’re looping through. The loop prints each color in the array, one by one.

Using for-of with Arrays

The for-of loop is an excellent choice for iterating over arrays because it directly accesses the values (elements) in the array, not the indices. This makes the loop more intuitive and readable when you’re dealing with the actual data.

The loop iterates through each element of the array, and the element variable (like num in the example) holds the current item from the array during each iteration.

const numbers = [10, 20, 30];

for (let num of numbers) {
  console.log(num);
}
// Output: 10, 20, 30

In this example:

  • numbers is the array being iterated over.
  • num represents each value in the array during the loop.
  • The loop prints 10, then 20, and finally 30.

Since the for-of loop gives direct access to the elements, it’s a preferred choice when you need to operate on the values themselves, not the array indices.

Using for-of with Strings

The for-of loop is not limited to arrays — it’s also great for iterating over strings. When using for-of with strings, the loop iterates over each character in the string one by one.

The loop treats the string as an iterable, where each character is accessed during each iteration. This allows you to perform operations on individual characters without needing to deal with string indices.

const greeting = 'Hello';

for (let char of greeting) {
  console.log(char);
}
// Output: H, e, l, l, o

In this example:

  • greeting is the string being iterated over.
  • char holds the current character during each iteration.
  • The loop prints each character in the string: H, e, l, l, o.

Using for-of with strings is a simple and effective way to work with individual characters in a string, without needing to use charAt() or other methods.

Using for-of with Sets

A Set is a collection of unique values in JavaScript, meaning it doesn’t allow duplicates. The for-of loop can be used to iterate over the values in a Set, making it easy to access each unique item without worrying about duplicates.

The for-of loop iterates through the unique values stored in the Set, one by one. Since Set does not have keys, only values are returned during the iteration.

const languages = new Set(["C", "Dart", "JavaScript", "Python"]);

for (let language of languages) {
  console.log(language);
}
// Output: C, Dart, JavaScript, Python

In this example:

  • languages is a Set containing three unique items: "C", "Dart", "JavaScript", and "Python".
  • language holds the current value during each iteration.
  • The loop prints each language in the set: C, Dart, JavaScript, Python.

The for-of loop simplifies iterating over Set objects, ensuring you only get the unique values stored within it.

Using for-of with Maps

A Map in JavaScript is a collection of key-value pairs, where each key is unique. The for-of loop can be used to iterate through these key-value pairs in a map.

When iterating over a Map with for-of, each iteration returns a key-value pair in the form of an array, where the first element is the key, and the second element is the value.

const capitals = new Map([["USA", "Washington, D.C."], ["Germany", "Berlin"]]);

for (let [country, capital] of capitals) {
  console.log(country, capital);
}
// Output: USA Washington, D.C., Germany Berlin

In this example:

  • capitals is a Map that contains two entries: one with "USA" as the key and "Washington, D.C." as the value, and another with "Germany" as the key and "Berlin" as the value.
  • The for-of loop iterates over each key-value pair, where [country, capital] destructures the pair into the country and capital variables.
  • The loop prints each country’s name followed by its capital: USA Washington, D.C., Germany Berlin.

Using for-of with maps is a convenient way to access both the keys and values without the need to separately query for each.

Accessing Index with for-of

The for-of loop in JavaScript is designed to iterate over the values of an iterable (like an array, string, or map). Unlike the for-in loop, which iterates over the keys or indices, for-of provides direct access to the values themselves. If you need the index during the iteration, you have to manually track it.

You can create a variable to keep track of the index and increment it as you iterate through the loop.

const numbers = [10, 20, 30];
let index = 0;

for (let num of numbers) {
  console.log(index, num);
  index++;
}
// Output: 0 10, 1 20, 2 30

In this example:

  • The for-of loop iterates over the numbers array, accessing each value (num), but since for-of doesn’t give you the index, we manually set index to track the position.
  • The index variable is incremented in each loop iteration, ensuring it matches the corresponding value’s position in the array.

While for-of doesn’t provide direct access to the index, this approach allows you to still keep track of the position within the loop when needed.

Using for-of with Iterables (Custom Objects)

In JavaScript, the for-of loop works with not just built-in iterable objects like arrays, strings, sets, and maps, but also with custom iterable objects. An iterable object is any object that implements the Symbol.iterator method. This method allows you to define how the object can be iterated over, making it possible to create your own objects that work with for-of loops.

To make an object iterable, you need to implement the Symbol.iterator method, which returns an iterator object. The iterator object must have a next() method that returns an object with two properties:

  • value: the current value in the iteration.
  • done: a boolean indicating whether the iteration is complete.
const range = {
    from: 1,
    to: 5,
    [Symbol.iterator]() {

      let current = this.from;
      let last = this.to;

      return {

        next() {

          if (current <= last) {
            return { value: current++, done: false };
          } else {
            return { done: true };
          }

        }

      };
    }
};

for (let num of range) {
  console.log(num);
}
// Output: 1, 2, 3, 4, 5

In this example:

  1. Custom Iterable Object (range): The range object has a from and to property, and it implements the [Symbol.iterator] method. The [Symbol.iterator] method returns an iterator object with the next() method, which defines the iteration logic.

  1. Iteration: Inside the next() method, it checks if the current value is less than or equal to the last value (this.to). If so, it returns the value (current number) and continues iterating. If not, it returns { done: true }, signaling the end of the iteration.

  1. Using for-of: The for-of loop iterates through the range object, calling the next() method on the iterator in each loop cycle until it’s done.

This approach shows how flexible the for-of loop is, allowing you to work with custom objects and define your own iteration logic.

Skipping Elements in for-of Loop

In JavaScript, you can skip certain elements in a for-of loop using the continue statement. The continue statement causes the loop to skip the current iteration and move to the next one. This is particularly useful when you want to ignore specific values or conditions during the loop execution.

How to use continue to skip elements:

  • The continue statement can be placed inside an if condition to skip over specific elements based on a certain condition.
  • Once continue is encountered, the rest of the loop body is skipped for that iteration, and the loop moves to the next element in the iterable.
const numbers = [1, 2, 3, 4, 5];

for (let num of numbers) {

  if (num === 3) continue; // Skip number 3
  console.log(num);

}
// Output: 1, 2, 4, 5

In this example:

  1. Array Iteration: The for-of loop iterates over each number in the numbers array.
  2. Condition to Skip: Inside the loop, there is a condition that checks if the number is 3. If it is, the continue statement is executed, which skips the current iteration and moves to the next number.
  3. Output: As a result, the number 3 is skipped, and the output is 1, 2, 4, 5.

This technique allows you to filter out specific values without breaking the loop completely, which can be very useful when dealing with large datasets or applying specific conditions to elements during iteration.

Breaking Out of a for-of Loop Early

In JavaScript, you can exit a for-of loop before it finishes iterating through all elements using the break statement. This is helpful when you no longer need to continue iterating, such as when a condition has been met and there’s no need to check the remaining items.

How to use break to exit the loop early:

  • The break statement immediately stops the loop and exits, skipping all remaining iterations.
  • This is useful when you find what you’re looking for and no longer need to process the rest of the data.
const numbers = [1, 2, 3, 4, 5];

for (let num of numbers) {

  if (num === 4) break; // Exit the loop when num is 4
  console.log(num);

}
// Output: 1, 2, 3

In this example:

  1. Array Iteration: The for-of loop iterates over each number in the numbers array.
  2. Condition to Break: Inside the loop, there is a condition that checks if the current number is 4. When it finds 4, the break statement is executed, which exits the loop immediately.
  3. Output: As a result, the loop stops after printing 1, 2, and 3, and 4 is never logged.

Using break is useful when you want to stop iterating through the elements early based on a condition, making your code more efficient in certain situations.

Best Practices

The for-of loop is best used for working with iterable data types—like arrays, strings, sets, and maps. To get the most out of it and avoid confusion, here are a few simple best practices to follow:

Use for-of with Iterables

Use the for-of loop when working with arrays, strings, sets, maps, or custom iterable objects. It lets you easily access each value without worrying about the index or keys.

const colors = ["red", "green", "blue"];

for (let color of colors) {
  console.log(color);
}
// Output: red, green, blue

Avoid Using for-of with Plain Objects

Regular objects (like { name: 'Edward' }) are not iterable, so using for-of with them will cause an error. Use for-in instead to loop through their keys.

const person = { name: "Edward", age: 30 };
// ❌ This will throw an error:
// for (let prop of person) { ... }

Convert Object Properties to Arrays When Needed

If you really want to use for-of with an object, convert its properties into an array first using Object.keys(), Object.values(), or Object.entries():

const person = { name: "Edward", age: 30 };

// Loop over keys
for (let key of Object.keys(person)) {
  console.log(key);
}
// Output: name, age

// Loop over values
for (let value of Object.values(person)) {
  console.log(value);
}
// Output: Edward, 30

// Loop over [key, value] pairs
for (let [key, value] of Object.entries(person)) {
  console.log(key, value);
}
// Output: name Edward, age 30

By following these tips, you’ll keep your loops clean, easy to understand, and best suited for the data you’re working with.

Conclusion

The for-of loop makes it easy to loop through items in arrays, strings, sets, maps, and other iterable things in JavaScript. It keeps your code simple and easy to read by giving you each value directly — no need to deal with indexes or keys.

Try using for-of in different situations, like looping over letters in a word, numbers in an array, or key-value pairs in a map. You can even use it with your own custom iterable objects!

In short, for-of is a clean and powerful tool when working with data structures that support it. With a little practice, you’ll find it super handy in your JavaScript projects.

Scroll to Top