DEV Community

Cover image for for of loop in JavaScript
Amer Sikira
Amer Sikira

Posted on • Originally published at webinuse.com

for of loop in JavaScript

This post was originally published on webinuse.com

We have already written about loops in JavaScript in the article JavaScript Arrays Loops. Now we will introduce a new one – for of loop.

for of loop is similar to forEach loop, but with for of loop we can use break and continue. This is something that makes it even more appealing.

The syntax for for of loop is pretty simple and straightforward.

The first parameter of for of loop is the loop variable and the second parameter is the array that we are iterating through. If we want to break out from the loop, we have to use keyword break.

const arr = [1, 2, 3];

for (const el of arr) {
   if (el === 3) break;
   console.log(el)
}

//Result
//1
//2
Enter fullscreen mode Exit fullscreen mode

Also, we can skip iteration by using keyword continue.

const arr = [1, 2, 3];

for (const el of arr) {
   if (el === 2) continue;
   console.log(el)
}

//Result
//1
//3
Enter fullscreen mode Exit fullscreen mode

Often, while working with loops we need to know the current index. We can accomplish that, with for of loop, by using entries().

const arr = ['js', 'py', 'php'];

for (const el of arr.entries()) {
   console.log(el)
}

//Result:
//[0, 'js']
//[1, 'py']
//[2, 'php']

Enter fullscreen mode Exit fullscreen mode

In the example above console.log returned the index and value of the current index, in the form of an array. But we can simplify this even further by destructuring the array. This means that we can extract values from the array, along with the index, as separate variables.


const arr = ['js', 'py', 'php'];

for (const [index, el] of arr.entries()) {
   console.log(index)
   console.log(el)
}

//Result:
//0
//js
//1
//py
//2
//php

Enter fullscreen mode Exit fullscreen mode

But we have to be careful if we are using destructuring. ALWAYS index comes the first and element comes the second. Also, we can use const in this case, because every new iteration for of loop creates a new scope.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like What is object destructuring in JavaScript?.

Top comments (0)