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 trialsidni ahmed
3,329 Pointswhy use 'while' loop instead of 'for'?
why use 'while' loop instead of 'for'? is there a big difference?
2 Answers
Steve Hunter
57,712 PointsHi there,
A for
loop runs for a pre-determined number of times. So, it can iterate through an array from start to finish, say, but it will only ever loop for that specific number.
A while
loop will carry on until a pre-determined scenario takes place. That may happen immediately, or it may require a hundred iterations. So, the number of loops is governed by an outcome, not a number. For example, you can continue looping until the user presses the Z
key (while keyPressed != 'Z'
) - the loop will constantly run until that happens. It may never happen.
A for
loop has it's bounds set from the beginning and, yes, while you can manipulate those bounds, the general implementation is such that the maximum number of loops is pre-determined.
I hope that makes sense!
Steve.
sidni ahmed
3,329 Pointsthanks a lot guys!
Steve Hunter
57,712 PointsNo problem! :-)
Jacob Mishkin
23,118 PointsJacob Mishkin
23,118 Pointsin general a while loop is used if you want an action to repeat itself until a certain condition is met i.e. if statement. An for loop is used when you want to iterate through an object. i.e. iterate through an array.