I know how to iterate over elements with for (const j of [1, 2, 3, 4, 5])
, but I’d like to get the index as well—without switching to forEach
or for-in
. Is there a way to include the for of JavaScript index
while keeping the for-of
loop style?
I’ve worked on a bunch of data-heavy UI interfaces, and trust me, clean iteration matters.
Here’s the most elegant method I always come back to—using .entries()
with for of
. It gives you both index and value without breaking the flow of the loop:
const nums = [10, 20, 30];
for (const [index, value] of nums.entries()) {
console.log(`Index: ${index}, Value: ${value}`);
}
Why this works: If you’re looking for a readable way to get the for of JavaScript index, this feels natural and keeps things tidy—especially when you’re mapping indexes to UI elements.
I’ve had to write quick debug utilities where changing loop structure wasn’t ideal.
Just adding on to what Tom said—if you don’t want to use .entries()
or destructuring, a manual counter still works great and is super flexible:
let index = 0;
for (const value of ['a', 'b', 'c']) {
console.log(`Index: ${index}, Value: ${value}`);
index++;
}
This lightweight trick helped me when I needed the for of JavaScript index without altering too much code. It’s simple, and it gets the job done fast.
In my last frontend project, numbering dropdown items dynamically was key.
Looping back (pun intended ), I used the
.entries()
method with a twist—adjusting the index for more human-friendly display:
const fruits = ['apple', 'banana', 'cherry'];
for (let [i, fruit] of fruits.entries()) {
console.log(`${i + 1}: ${fruit}`);
}
Using this with for of JavaScript index not only kept my dropdown clean but also made the numbering user-readable, without any extra library. Destructuring here just feels built-in once you get used to it.