Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Quickstart Arrays and Loops Simplify Repetitive Tasks with a forEach Loop

Sean Flanagan
Sean Flanagan
33,235 Points

forEach vs for

Hi.

What advantage do forEach loops have over for loops?

1 Answer

Steven Parker
Steven Parker
229,005 Points

A "forEach" isn't exactly a loop, it's an array method. So one difference is that you cannot use a "break" or "continue" in it.

But when you want to do something with every array element it can be handy, since it gets passed both the element and the index as arguments.

Another advantage is that it only acts on elements that have been assigned values, so it needs no special testing code when using it on "sparse" arrays.

For more details, see the reference page on MDN.