How to Get the Index of a for-of Loop Iteration in JavaScript
The for-of
loop changed the way JavaScript (ES6) handles iterables, but accessing indexes like in a traditional for
loop can be confusing.
There’s no native feature in the for-of
loop that gives us the iteration index.
Luckily, we can use .entries()
to access the current index.
const arr = ['corgi', 'shih tzu', 'pug'];
for(let elem of arr.entries()) {
console.log(`Element: ${elem}`);
}
// [0, 'corgi']
// [1, 'shih tzu']
// [2, 'pug']
This means that we can destructure the output of .entries()
to obtain the index in the for-of
loop.
const arr = ['corgi', 'shih tzu', 'pug'];
for(let [index, elem] of arr.entries()) {
console.log(`Index: ${index}`);
console.log(`Element: ${elem}`);
}