How to get an index in for-of-loop | index in for-of-loop

The for…of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

for (variable of iterable) {
  statement
}

Example:

const iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30

But some time we want to access index of each element. For this purpose we can use counter.

let counter = 0
const iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value, counter);
  counter += 1;
}
// 10, 0
// 20, 1
// 30, 2

There is another way to get index using entries() on array.

const iterable = [10, 20, 30];

for (const [index, value] of iterable.entries()) {
  console.log(value, index);
}
// 10, 0
// 20, 1
// 30, 2

Leave a Reply