[Go Make Things] Getting the index in a for...of loop

I love for...of loops!

I find them nice and simple. They're more clear than an old-school forloop, 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);  }  

Here's a demo on CodePen.

Like this? A Go Make Things membership is the best way to support my work and help me create more free content.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+ Lintasme

Related Post:

0 Komentar untuk "[Go Make Things] Getting the index in a for...of loop"

Back To Top