DEV Community

Cover image for How to get the index of the current item in a for...of looping statement in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the index of the current item in a for...of looping statement in JavaScript?

Originally posted here!

To get the index of the current item being looped in a for...of looping statement in JavaScript, you need to make the iterable into a key: value pair in case of strings or an Array iterator in case of an array and then use the array destructuring to get the index as the first value and the current looped value as the second.

This is because the native for...of looping statement doesn't provide the index of the current item.

TL;DR

// array
const arr = [1, 2, 3, 4, 5];

// for...of loop
for (const [index, value] of arr.entries()) {
  console.log(index + ":" + value);
}

/*
OUTPUT:

0:1
1:2
2:3
3:4
4:5

*/
Enter fullscreen mode Exit fullscreen mode

For Arrays

Consider this array of strings,

// Strings array
const strArr = ["John", "Roy", "Lily"];

// for...of loop
for (let [index, value] of strArr.entries()) {
  console.log(index + ":" + value);
}

/*
OUTPUT:

0:John
1:Roy
2:Lily

*/
Enter fullscreen mode Exit fullscreen mode

Here, we are making the strArr (Array of strings) into an Array iterator using the array entries() method, so that we can get the index as the first value and the current looped value as the second.

See the example live in JSBin

For Strings

Consider this string,

// A String
const str = "Hello World!";

// for...of loop
for (let [index, value] of Object.entries(str)) {
  console.log(index + ":" + value);
}

/*
OUTPUT:

0:H
1:e
2:l
3:l
4:o
5: 
6:W
7:o
8:r
9:l
10:d
11:!

*/
Enter fullscreen mode Exit fullscreen mode

Here, we are making the str (String) into a key: value pair using the Object.entries() method, so that we can get the index as the first value and the current looped value as the second.

See the example live in JSBin

Feel free to share if you found this useful 😃.


Top comments (0)