This content originally appeared on Go Make Things and was authored by Go Make Things
I love for...of
loops!
I find them nice and simple. They’re more clear than an old-school for
loop, and in my opinion easier to read than an Array.prototype.forEach()
method (or the NodeList
equivalent).
const wizards = ['Merlin', 'Gandalf', 'Radagast'];
for (const wizard of wizards) {
console.log(wizard);
}
But sometimes, you need the index
of the item you’re looping over, and the for...of
loop doesn’t give you that.
Historically, that means I’ve had to rely on the .forEach()
method, or .map()
, or something similar.
wizards.forEach((wizard, index) => {
console.log(wizard, index);
});
It works, it’s fine, whatever.
But there are some important differences. You can’t continue
in a .forEach()
callback. You return
to end the current callback function and jump to the next one.
And you can’t break
to end the loop early. It has to loop over all items. No exceptions.
wizards.forEach((wizard, index) => {
// This is NOT a thing!
if (wizard === 'Gandalf') break;
});
While working on a recursive function for generating nested Table of Contents HTML for Kelp, I decided to look into how I might use a for...of
loop and still have access to an index
.
And I (re)discovered the Array.prototype.entries()
and NodeList.prototype.entries()
methods.
This work more-or-less just like the Object.prototype.entries()
method, returning an iterator you can loop over. But instead of giving the key
and value
, they give you the index
and value
.
You can then destructure the array to access the index
in the loop.
for (const [index, wizard] of wizards.entries()) {
console.log(wizard, index);
}
Like this? A Lean Web Club membership is the best way to support my work and help me create more free content.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2025-07-14T14:30:00+00:00) Getting the index in a for…of loop. Retrieved from https://www.scien.cx/2025/07/14/getting-the-index-in-a-for-of-loop/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.