Access to ES6 array element index inside for-of loop

Use Array.prototype.keys:

for (const index of [1, 2, 3, 4, 5].keys()) {
  console.log(index);
}

If you want to access both the key and the value, you can use Array.prototype.entries() with destructuring:

for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
  console.log(index, value);
}

In this world of flashy new native functions, we sometimes forget the basics.

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}

Clean, efficient, and you can still break the loop. Bonus! You can also start from the end and go backwards with i--!

Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i]; at the top of the loop for an easy, readable reference.


Array#entries returns the index and the value, if you need both:

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

}

In a for..of loop we can achieve this via array.entries(). array.entries returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.

When the next() method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.

let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']

A for..of loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries() in the following manner:

array = ['a', 'b', 'c'];

for (let indexValue of array.entries()) {
  console.log(indexValue);
}


// we can use array destructuring to conveniently
// store the index and value in variables
for (let [index, value] of array.entries()) {
   console.log(index, value);
}