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

While loop and for loop

So while loop and for loop do the same thing but when do we use while and for loop, is there any particular role for while and for loop?

2 Answers

Joel Sprunger
Joel Sprunger
5,448 Points

A for loop is usually used for a loop that executes a set number of times and a while loop is something that executes until a condition is met. They can be used interchangeably by exiting the for loop, or by putting a counter in the while loop. I prefer to only use a for loop. If you do want to use a while loop, it is good to put some form of exit if the condition isn't met, otherwise it can turn into an infinite loop (usually because there is a logical bug). If you put a counter in the while loop and exit the loop if the counter gets above 10,000 then the loop will not lock up the program.

I like this answer:

https://stackoverflow.com/a/6710639

The post is about Java, but the concept is the same.

Thank u

np! You can mark this question as solved by selecting a "best answer". :smile: