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 Simplify Repetitive Tasks with Loops For Loops

Jonathan Martinez
seal-mask
.a{fill-rule:evenodd;}techdegree
Jonathan Martinez
Full Stack JavaScript Techdegree Student 6,439 Points

For loop vs. Do/While loop vs. While Loop

Hi, I wouldn't particularly say I'm completely new to JavaScript, but I'm new enough to not understand when and where you would use different loop types. My understanding of for loops is far better than my understanding of do/while or while loops. So my question is, is there a place I can go or read up on to figure out why I would need each different loop? The open sesame exercise in the previous lesson was extremely confusing to me and seemed way complicated.

2 Answers

You use the loop that is best suited for the job. For example, if you know exactly how many times you want to iterate(loop) over something then you would go ahead and use the for loop. looping 10 times to print 1 through 10 would be a good example of when to use a for loop. Now the Do While loop would be used when you have no idea how many times you would need to loop over something. Lets say that you built a form and your user is signing in, you want to keep asking for the login credentials UNTIL he enters the right credentials. In this case you aren't really sure whether it will take him three tries before he enters the right username and password or get it right on the first attempt.

Jonathan Martinez
seal-mask
.a{fill-rule:evenodd;}techdegree
Jonathan Martinez
Full Stack JavaScript Techdegree Student 6,439 Points

That actually makes a lot of sense. So just so I understand, if the amount of times you had to run through the loop was unknown, you would want to use a do while loop because we technically wouldn't have any idea how many times a user would enter the correct information, but in the case of where you have a form and the form says, you have 4 more times to enter the correct information, you would use a for loop. Correct?

Yes exactly!

jag
jag
18,266 Points

There are a lot of examples on MDN.