In the JavaScript for...of
loop, you can use the Array.prototype.entries()
method to get both, the index and the corresponding value of each element, for example, like so:
const arr = ['apple', 'banana', 'orange']; for (const [index, value] of arr.entries()) { console.log(`${index}: ${value}`); } // '0: apple' // '1: banana' // '2: orange'
In this example, arr.entries()
returns an array iterator that produces an array of [index, value]
pairs for each element in the array. To illustrate this, consider the following code:
const arr = ['apple', 'banana', 'orange']; const iterator = arr.entries(); // Array Iterator console.log(iterator.next().value); // [0, 'apple'] console.log(iterator.next().value); // [1, 'banana'] console.log(iterator.next().value); // [2, 'orange'] console.log(iterator.next().value); // undefined
As you can see, the iterator object contains the key/value pairs for each index in the array. These can be accessed in a for...of
loop by using the destructuring syntax:
for (const [index, value] of arr.entries()) { // ... }
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.