How do you get the index while iterating?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Most array methods hand you the index as the second argument:
const items = ["a", "b", "c"];
items.forEach((value, i) => console.log(i, value));
items.map((value, i) => `${i}: ${value}`);
items.filter((value, i) => i % 2 === 0);
for...of does not, but entries() pairs each value with its index and destructures cleanly:
for (const [i, value] of items.entries()) {
console.log(i, value);
}
This is the one to reach for when the body is asynchronous or needs break.
Do not use for...in on arrays
It iterates keys, which come back as strings, and it walks inherited enumerable properties too:
for (const i in items) {
i + 1; // "01", not 1 — i is a string
}
Choosing between them
| Need | Use |
|---|---|
| Side effects for each item | forEach |
| A new array | map |
break / continue | for...of with entries() |
await inside the loop | for...of — forEach will not wait |
| Maximum speed on huge arrays | classic for |
The await row is the one that bites people:
items.forEach(async (x) => { await save(x); }); // returns immediately
for (const [i, x] of items.entries()) await save(x); // actually sequential
forEach ignores the promise its callback returns, so the surrounding code continues before any save finishes.
If you want the index inside a while or a manual loop, keep a counter — but in modern code that is rarely necessary. And findIndex or indexOf are the right tools when you want the position of one specific item rather than every position.
