DEV Community

Cover image for JavaScript for...of loop
Moazam Ali
Moazam Ali

Posted on

JavaScript for...of loop

For…of loop

The for…of loop was introduced in the later versions of JavaScript ES6.

The JavaScript for…of loop is used to iterate over the values of the iterable object. These Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments _object, _generators produced by generator functions, and user-defined iterables.

A for...of loop operates on the values sourced from an iterable one by one in sequential order. for…of loop provides clean code and minimizes the clutter of JavaScript for loops.

 

for loop

 

let colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}
Enter fullscreen mode Exit fullscreen mode

Output:

red
green
blue
Enter fullscreen mode Exit fullscreen mode

 

for…of loop

 

let colors = ['red', 'green', 'blue'];
for (let i of colors) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

red
green
blue
Enter fullscreen mode Exit fullscreen mode

 

Syntax

for(variable of iterable){
    // body of for…of loop
    statement(s)
}
Enter fullscreen mode Exit fullscreen mode

variable
JavaScript variable declared with either const, let, or var, which receives value from the sequence on each iteration.

iterable
Iterable is the iterable object on which the loop operates. It is the source for the sequence of values.

statement
It could be a single statement or multiple statements that are to be executed on every iteration.

 

for…of with Arrays

The for…of loop can be used to iterate over the values of an Array. For example:

// array
let colors = ['red', 'green', 'blue'];

// using for...of loop
for (let i of colors) {
    // display the values in console
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

red
green
blue
Enter fullscreen mode Exit fullscreen mode

 

for…of with Strings

The for…of loop can be used to iterate over the values of an Array. For example:

// string
let myString = "Hello";

// using for...of loop
for (let i of myString) {
    // display the values in console
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

H
e
l
l
o
Enter fullscreen mode Exit fullscreen mode

 

Wrapping up!

The for...of loop cannot be used to iterate over an object and this is where for…in loop comes in. The for...of loop was introduced in ES6. Some browsers may not support its use.

💻 Happy Coding

Latest comments (0)