Get the current index in a JavaScript for…of loop

OpenJavaScript 0

Last updated: November 15, 2023.

It is often useful to get the current index value inside a loop. But the index value is not immediately available in a for...of loop.

For example, trying to access the index value after the current value of the iterable being looped through causes an error to be thrown:

const array = ["x", "y", "z"];

for (value, index of array) { // Uncaught SyntaxError: Invalid left-hand side in for-loop 

    console.log(index);
    console.log(value);

};

The solution is to transform the iterable from a simple iterable (no nesting) into an array of arrays, in which each nested array contains a value from the simple array and its index position.

To make this transformation, you can call the entries() method on the iterable.

In case you cannot call entries() on your iterable, you can first spread its contents into an array ([...myList]). The entries() method will then be available on the array.

Each nested array (entry) now contains its index value and corresponding value from the original array:

const entries = array.entries();

for (entry of entries) {
    console.log(entry); // [0, "x"], [1, "y"], [2, "z"], 
};

Now, each time the loop runs, you can use destructuring syntax to extract the current index and value from the current entry:

const array = ["x", "y", "z"];

for ([index, value] of array.entries()) {

    console.log(index); // 0, 1, 2
    console.log(value); // x, y, z

};