Categories
JavaScript Answers

How to Get the Loop Counter or Index Using for-of Loop in JavaScript?

Spread the love

The for-of loop is an easy-to-use loop that comes with JavaScript that lets us loop through arrays and iterable objects easily.

However, there’s no way to get the index of the element being looped through with it directly.

In this article, we’ll look at how to get the loop counter or index with the for-of loop in JavaScript.

Array.prototype.forEach

One way to get the index while iterating through an array is to use the forEach method.

We can pass in a callback with the index of the item being looped through in the 2nd parameter.

So we can write:

const arr = [565, 15, 642, 32];
arr.forEach((value, i) => {
  console.log('%d: %s', i, value);
});

We call forEach with a callback that has the value with the value in arr being iterated through.

i has the index of value .

And so we get:

0: 565
1: 15
2: 642
3: 32

Array.prototype.entries

JavaScript arrays also have the entries method to return an array of arrays with the index of the item and the item itself.

For instance, we can write:

const arr = [565, 15, 642, 32];
for (const [i, value] of arr.entries()) {
  console.log('%d: %s', i, value);
}

We destructure the index and value from the array entry and then we log both values with the console log.

So we get:

0: 565
1: 15
2: 642
3: 32

as a result.

Conclusion

There are several ways we can use to loop through an array and access the index and the value of the entry during each iteration.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *