JavaScript for...of loop
Moazam Ali
Posted on October 4, 2022
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]);
}
Output:
red
green
blue
for…of
loop
let colors = ['red', 'green', 'blue'];
for (let i of colors) {
console.log(i);
}
Output:
red
green
blue
Syntax
for(variable of iterable){
// body of for…of loop
statement(s)
}
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);
}
Output:
red
green
blue
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);
}
Output:
H
e
l
l
o
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
Posted on October 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024