aderaaij
11/14/2017 - 9:42 PM

ES6 - For...of loop with index

A way to get a for loop with an index. For this we use Array.entries which returns an ArrayIterable which we can go over with array.entries().next(); Each time you call next() it will return an object with a done: status which has a boolean value and an array of the current array item and its index.

// In the for loop we directly destructure the array returned by heroes.entries();
for (const[i, hero] of heroes.entries()) {
    console.log(`${hero} is hero #${i + 1}`);
}