Skip to main content

JavaScript For Of Loop

Introduction

The for...of loop is a modern JavaScript feature introduced in ES6 (ECMAScript 2015) that provides a simple and elegant way to iterate over iterable objects. Unlike the traditional for loop or the forEach() method, the for...of loop offers a more readable syntax for working with collections of data.

An iterable is any JavaScript object that can be looped over. Common iterables include:

  • Arrays
  • Strings
  • Maps
  • Sets
  • NodeLists (DOM elements)
  • Arguments object

Basic Syntax

The basic syntax of a for...of loop looks like this:

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

Where:

  • element is a variable that represents the current value in each iteration
  • iterable is any iterable object (array, string, etc.)

Using For...Of Loop with Arrays

Arrays are one of the most common iterables you'll use with the for...of loop.

Example: Iterating through an array

const fruits = ['apple', 'banana', 'cherry', 'date'];

for (const fruit of fruits) {
console.log(fruit);
}

Output:

apple
banana
cherry
date

Notice how clean and straightforward this is compared to a traditional for loop:

// Traditional for loop (more verbose)
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

Using For...Of Loop with Strings

Strings are also iterable in JavaScript, allowing us to loop through each character.

Example: Iterating through a string

const greeting = 'Hello';

for (const character of greeting) {
console.log(character);
}

Output:

H
e
l
l
o

Using For...Of Loop with Other Iterables

Maps

Maps are collections of key-value pairs that remember the original insertion order of the keys.

const userRoles = new Map([
['John', 'admin'],
['Jane', 'editor'],
['Bob', 'subscriber']
]);

for (const entry of userRoles) {
console.log(entry);
}

Output:

['John', 'admin']
['Jane', 'editor']
['Bob', 'subscriber']

You can also destructure the entries directly:

for (const [user, role] of userRoles) {
console.log(`${user} has role: ${role}`);
}

Output:

John has role: admin
Jane has role: editor
Bob has role: subscriber

Sets

Sets are collections of unique values.

const uniqueNumbers = new Set([1, 2, 3, 4, 4, 5]);

for (const number of uniqueNumbers) {
console.log(number);
}

Output:

1
2
3
4
5

DOM NodeLists

When you select elements from the DOM, you often get a NodeList, which is also iterable.

// Assuming you have multiple paragraphs in your HTML
const paragraphs = document.querySelectorAll('p');

for (const paragraph of paragraphs) {
paragraph.style.color = 'blue';
console.log(paragraph.textContent);
}

Practical Examples

Example 1: Calculate total price from a shopping cart

const shoppingCart = [
{ item: 'Laptop', price: 999.99 },
{ item: 'Headphones', price: 129.50 },
{ item: 'Mouse', price: 29.99 },
{ item: 'Keyboard', price: 59.95 }
];

let totalPrice = 0;

for (const product of shoppingCart) {
totalPrice += product.price;
}

console.log(`Total price: $${totalPrice.toFixed(2)}`);

Output:

Total price: $1219.43

Example 2: Filtering elements on the fly

const scores = [85, 92, 78, 65, 98, 74];
const passingScores = [];

for (const score of scores) {
if (score >= 70) {
passingScores.push(score);
console.log(`${score} is a passing score!`);
}
}

console.log('All passing scores:', passingScores);

Output:

85 is a passing score!
92 is a passing score!
98 is a passing score!
74 is a passing score!
All passing scores: [85, 92, 98, 74]

Example 3: Working with nested arrays

const classrooms = [
['Alice', 'Bob', 'Charlie'],
['Diana', 'Eve', 'Frank'],
['Grace', 'Heidi', 'Ivan']
];

for (const classroom of classrooms) {
console.log('Classroom students:');

for (const student of classroom) {
console.log(`- ${student}`);
}

console.log('---');
}

Output:

Classroom students:
- Alice
- Bob
- Charlie
---
Classroom students:
- Diana
- Eve
- Frank
---
Classroom students:
- Grace
- Heidi
- Ivan
---

For...Of vs For...In

It's important to note the difference between for...of and for...in:

  • for...of: Iterates over the values of an iterable
  • for...in: Iterates over the enumerable property names (keys) of an object
const colors = ['red', 'green', 'blue'];

// for...of loop (values)
for (const color of colors) {
console.log('Value:', color);
}

// for...in loop (indices)
for (const index in colors) {
console.log('Index:', index, 'Value:', colors[index]);
}

Output:

Value: red
Value: green
Value: blue
Index: 0 Value: red
Index: 1 Value: green
Index: 2 Value: blue

Breaking and Continuing in For...Of Loops

Just like other loops, you can use break to exit the loop early and continue to skip to the next iteration.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log('Breaking example:');
for (const num of numbers) {
if (num > 5) {
break;
}
console.log(num);
}

console.log('Continuing example:');
for (const num of numbers) {
if (num % 2 === 0) {
continue;
}
console.log(num);
}

Output:

Breaking example:
1
2
3
4
5
Continuing example:
1
3
5
7
9

Summary

The for...of loop is a powerful and elegant way to iterate over JavaScript iterables. Its simple syntax makes your code more readable and maintainable compared to traditional for loops.

Key takeaways:

  • The for...of loop works with any iterable object (arrays, strings, maps, sets, etc.)
  • It provides the value directly, without needing to use an index
  • It's cleaner and less error-prone than traditional for loops
  • You can use break and continue statements within the loop
  • Unlike forEach(), you can use await inside a for...of loop

Practice Exercises

  1. Create a function that takes an array of numbers and returns the sum of all even numbers using a for...of loop.

  2. Write a program that counts the occurrences of each character in a string using a for...of loop and a Map.

  3. Create a function that flattens a nested array (an array of arrays) into a single array using a for...of loop.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)