Explain Codes LogoExplain Codes Logo

Access to ES6 array element index inside for-of loop

javascript
loop-control
iterator-protocol
array-indexing
Alex KataevbyAlex Kataev·Oct 12, 2024
TLDR

Surely implement array.entries() with for-of for a clear indexed loop:

for (const [index, value] of ['a', 'b', 'c'].entries()) { console.log(index, value); // 0 'a', 1 'b', 2 'c' }

Pairs index with value, making iteration simple and readable.

When you need the index

Indexing with array.keys()

If you're more interested in the indices than the values, array.keys() focuses only on them:

for (const index of ['a', 'b', 'c'].keys()) { console.log(index); // 0, 1, 2 - *counting* to solve *indexing*. Who knew? }

Indexing in a pure for-of loop

You can also keep track of the index the old-fashioned way, with some manual labor:

let index = 0; for (const value of ['a', 'b', 'c']) { console.log(index++, value); // 0 'a', 1 'b', 2 'c' - indices breaking free! }

Ultimate control with traditional for

When you need sophisticated control over your loop, for loop is the swiss-army knife of looping:

let arr = ['a', 'b', 'c']; for (let i = arr.length - 1; i >= 0; i--) { console.log(i, arr[i]); // 2 'c', 1 'b', 0 'a' - back to front, because why not? }

Behind the scenes with .next()

Underneath the hood of for-of loops lies the iterator protocol:

const entriesIterator = ['a', 'b', 'c'].entries(); let result = entriesIterator.next(); while (!result.done) { console.log(result.value); // [0, 'a'], [1, 'b'], [2, 'c'] result = entriesIterator.next(); }

Beware of forEach and for-in

forEach and for-in may not behave as expected for array iteration:

['a', 'b', 'c'].forEach((value, index) => { // Ghost-ridin' the loop. No breaks. }); for (const prop in ['a', 'b', 'c']) { if (['a', 'b', 'c'].hasOwnProperty(prop)) { // prop could be a method or property name, or a spice for all we know. } }

Could a simple for loop be the way to go? Take your pick.