for…of Loop

Introduction

The for...of loop is a modern looping statement introduced in ECMAScript 6 (ES6). It is used to iterate over the values of iterable objects such as arrays, strings, maps, sets, and other iterable collections.

Unlike the traditional for loop, you do not need to manage an index variable manually. The for...of loop automatically retrieves each value one by one, making the code cleaner, shorter, and easier to read.

For automation engineers, the for...of loop is widely used to iterate through web elements, test data, JSON arrays, CSV records, API responses, and collections of browser objects.


What is a for...of Loop?

A for...of loop iterates over the values of an iterable object.

Instead of accessing values using an index, JavaScript automatically assigns each value to a loop variable during every iteration.


Syntax

for (const value of iterable) {

    // Code to execute

}

Flow of Execution

Start
   │
   ▼
Get First Value
   │
   ▼
Execute Code
   │
   ▼
Get Next Value
   │
 ┌─┴─────────────┐
 │               │
More Values?    No
 │               │
 ▼               ▼
Repeat          End

Why Do We Use for...of Loops?

The for...of loop helps developers:

  • Iterate through arrays easily.

  • Avoid managing index variables.

  • Improve code readability.

  • Work with iterable objects efficiently.

  • Write cleaner and more modern JavaScript code.


Basic Example

const fruits = ["Apple", "Banana", "Orange"];

for (const fruit of fruits) {

    console.log(fruit);

}

Output

Apple
Banana
Orange

Iterating Through Numbers in an Array

const numbers = [10, 20, 30, 40];

for (const number of numbers) {

    console.log(number);

}

Output

10
20
30
40

Iterating Through a String

A string is also an iterable object.

const language = "JavaScript";

for (const letter of language) {

    console.log(letter);

}

Output

J
a
v
a
S
c
r
i
p
t

Iterating Through a Set

const colors = new Set(["Red", "Green", "Blue"]);

for (const color of colors) {

    console.log(color);

}

Output

Red
Green
Blue

Iterating Through a Map

const employees = new Map([
    [101, "John"],
    [102, "Alice"],
    [103, "David"]
]);

for (const [id, name] of employees) {

    console.log(id, name);

}

Output

101 John
102 Alice
103 David

Real-World Example

Suppose an online shopping application displays product names.

const products = ["Laptop", "Mouse", "Keyboard"];

for (const product of products) {

    console.log(product);

}

Output

Laptop
Mouse
Keyboard

Another example:

const cities = ["Delhi", "Mumbai", "Bengaluru"];

for (const city of cities) {

    console.log(`Delivering to ${city}`);

}

Output

Delivering to Delhi
Delivering to Mumbai
Delivering to Bengaluru

Automation Testing Example

Automation engineers commonly use for...of loops to iterate through collections of web elements and test data.

Playwright Example

Click every button on a page.

const buttons = await page.locator("button").all();

for (const button of buttons) {

    await button.click();

}

Selenium Example

Print the text of all links.

const links = await driver.findElements(By.tagName("a"));

for (const link of links) {

    console.log(await link.getText());

}

API Testing Example

Validate users returned by an API.

const users = ["Alice", "Bob", "Charlie"];

for (const user of users) {

    console.log(`Validating ${user}`);

}

Output

Validating Alice
Validating Bob
Validating Charlie

Data-Driven Testing Example

const browsers = ["Chrome", "Firefox", "Edge"];

for (const browser of browsers) {

    console.log(`Running tests on ${browser}`);

}

Output

Running tests on Chrome
Running tests on Firefox
Running tests on Edge

for Loop vs for...of Loop

Traditional for Loop

const fruits = ["Apple", "Banana", "Orange"];

for (let i = 0; i < fruits.length; i++) {

    console.log(fruits[i]);

}

for...of Loop

const fruits = ["Apple", "Banana", "Orange"];

for (const fruit of fruits) {

    console.log(fruit);

}

The for...of version is shorter and easier to read because there is no need to manage an index variable.


for...of vs for...in

Suppose you have an array:

const fruits = ["Apple", "Banana", "Orange"];

for...of

for (const fruit of fruits) {

    console.log(fruit);

}

Output

Apple
Banana
Orange

for...in

for (const index in fruits) {

    console.log(index);

}

Output

0
1
2

for...of returns values, while for...in returns property names or indexes.


Common Mistakes

Using for...of with Plain Objects

Incorrect:

const person = {

    name: "John",

    age: 25

};

for (const value of person) {

    console.log(value);

}

This produces an error because plain objects are not iterable.


Modifying the Loop Variable

Incorrect:

for (const number of [1, 2, 3]) {

    number++;

}

const variables cannot be reassigned.

If modification is required, use let.


Using for...of When the Index Is Needed

If you need the array index, use a traditional for loop or array methods such as entries().


Best Practices

Use const Whenever Possible

If the loop variable does not need reassignment:

for (const item of items)

This prevents accidental modifications.


Use for...of for Arrays

It is the preferred way to iterate over array values in modern JavaScript.


Keep Loop Logic Simple

Avoid placing excessive business logic inside the loop body.


Use Meaningful Variable Names

Instead of:

for (const x of users)

Use:

for (const user of users)

This improves readability.


Conclusion

The for...of loop is a modern and efficient way to iterate through iterable objects in JavaScript. It eliminates the need for index management and produces cleaner, more readable code.

For automation engineers, the for...of loop is particularly useful for iterating through arrays of web elements, test data, API responses, JSON records, and browser collections. It is one of the most commonly used loops in modern JavaScript automation frameworks.


Frequently Asked Questions (FAQs)

What is a for...of loop in JavaScript?

A for...of loop iterates over the values of iterable objects such as arrays, strings, sets, and maps.


What is the syntax of a for...of loop?

for (const value of iterable) {

    // Code

}

Which data structures support for...of?

for...of works with:

  • Arrays

  • Strings

  • Sets

  • Maps

  • Other iterable objects


Can for...of iterate over plain JavaScript objects?

No. Plain objects are not iterable. To iterate over object properties, use a for...in loop or methods like Object.keys() or Object.entries().


Why is the for...of loop useful in automation testing?

Automation engineers use for...of loops to iterate through web elements, test data, JSON arrays, API responses, CSV records, and browser collections, making automation scripts cleaner and easier to maintain.


Key Takeaways

  • The for...of loop iterates over the values of iterable objects.

  • It works with arrays, strings, sets, maps, and other iterables.

  • It eliminates the need for index management.

  • It produces cleaner and more readable code than traditional for loops.

  • Use const for the loop variable whenever possible.

  • Plain JavaScript objects are not iterable with for...of.

  • Use for...of when you need values, not indexes.

  • It is widely used in modern JavaScript development.

  • It is commonly used in Selenium, Playwright, Cypress, and API automation.

  • Mastering the for...of loop helps write concise, readable, and maintainable JavaScript code.