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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1 Solution

Was there a reason for using a for loop over the other loops for this assignment?

I guess I'm curious about what kinds of settings what prefer one form of loop over another.

1 Answer

Steven Parker
Steven Parker
228,978 Points

It's often possible to implement what you need more than one way. Loop choice can be just based on convenience.

If you know at the start what the initialization conditions should be, what to test to continue, and what to increment for each iteration, the "for" loop is handy because you define them all at once.

A "while" loop might work better if a variety of things might change between iterations, and/or the initialization conditions are present before the loop starts.

And the "do...while" is good for when the loop code needs to be performed before you can test the exit condition.

A "for...in" is great for working with objects where you need the keys, and "for...of" when you only need the values.

And finally, a "forEach" method is handy for arrays or other types of collections that have one.

Does that help?

That is really helpful thank you!