JavaScript for…of Loop

The for...of loop in JavaScript provides a simple and convenient way to iterate over iterable objects such as arrays, strings, maps, sets, and more. It retrieves the values of the elements directly without needing to access the index.

1. Syntax of for...of Loop:

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

Try It Now

Explanation:

  • element: The variable that holds the value of the current element in the iteration.
  • iterable: The collection or object being iterated over, such as an array or string.

 

2. Example of for...of Loop with Arrays:

let fruits = ["Apple", "Banana", "Cherry"];

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

Try It Now

Output:

Apple
Banana
Cherry

Try It Now

3. for...of Loop with Strings:

let word = "Hello";

for (let char of word) {
    console.log(char);
}

Try It Now

Output:

H
e
l
l
o

Try It Now

Explanation:

  • The loop iterates over each character in the string.

4. Using for...of with Maps:

let map = new Map();
map.set("name", "John");
map.set("age", 30);

for (let [key, value] of map) {
    console.log(`${key}: ${value}`);
}

Try It Now

Output:

name: John
age: 30

Try It Now

Explanation:

  • for...of iterates over the entries of the Map object, retrieving both keys and values.

 

5. Using for...of with Sets:

let set = new Set(["Apple", "Banana", "Cherry"]);

for (let item of set) {
    console.log(item);
}

Try It Now

Output:

Apple
Banana
Cherry

Try It Now

Explanation:

  • for...of iterates over the unique elements of a Set.

 

6. Comparing for...of with forEach:

  • for...of works on all iterable objects and is generally preferred when you need to iterate over the values of an array or collection directly.
  • forEach is specifically for arrays and allows for more control over the execution of functions for each element.

7. for...of with break and continue:

Unlike forEach, you can use break and continue with for...of.

Using break:

let fruits = ["Apple", "Banana", "Cherry"];

for (let fruit of fruits) {
    if (fruit === "Banana") {
        break;
    }
    console.log(fruit);
}

Try It Now

Output:

Apple

Try It Now

Using continue:

for (let fruit of fruits) {
    if (fruit === "Banana") {
        continue;
    }
    console.log(fruit);
}

Try It Now

Output:

Apple
Cherry

Try It Now

Conclusion:

  • The for...of loop is a powerful and easy-to-use construct for iterating over iterable objects.
  • It simplifies accessing values directly, making code cleaner and more readable.
  • The ability to use break and continue makes it more flexible compared to forEach.