JavaScript For of Loop

The JavaScript for of loop is a control flow statement used to iterate over a sequence of values. It is used to loop through the items in an array, object, or string. It is the most commonly used looping structure in JavaScript and is used to execute a block of code multiple times until a certain condition is met.

Why should you use it?

  • It is easy to use and understand.
  • It is faster than other looping structures.
  • It can be used to iterate over both objects and arrays.

For...of Loop

The for...of statement creates a loop iterating over iterable objects such as arrays, strings, maps, node lists, and more. It is similar to the for...in statement, but it only iterates over the values of the iterable object, not the keys.

The syntax for the for...of statement is:

index.js
for (variable of iterable) {
  code block to be executed
}

The for...of statement iterates over the values of an iterable object. The loop will run once for each value in the iterable object. The value of the current element is stored in a variable inside the loop.

Let's look at an example. We have an array of colors:

index.js
const colors = ['red', 'green', 'blue'];

We can use a for...of loop to iterate over the array:

index.js
for (const color of colors) {
  console.log(color);
}

The loop will run three times, once for each element in the array. On each iteration, the value of the current element is stored in the variable color. We can use the variable color to display each element in the array:

index.js
for (const color of colors) {
  console.log('The color is ' + color);
}

The output of the code above will be:

index.js
The color is red
The color is green
The color is blue