+ 1

While vs For loop, differences and which is better?

What is the difference between while and for loop and which one to use.

8th Sep 2016, 12:27 AM
Roshan Abady
Roshan Abady - avatar
2 Respuestas
+ 4
They are pretty much equivalent. Using for loops allows you to have the init, condition and increment all in one place, which is nice for readability. var i = 0 while (i < 5) { //... i++; } is equivalent to for (var i = 0; i < 5; i++) { //... }
8th Sep 2016, 12:45 AM
Zen
Zen - avatar
+ 4
* For loop: Mostly used when you know how many repetitions are needed. Example: × Count to 10. × Iterate through a whole list. * While loop: Mostly used when you don't know how many repetitions you need. Example: × Pick a random number until you pick 7. × Iterate through the list of names until you find "Roshan". Bonus fact: It has also been scientifically proven that a For loop can always be converted to a While loop, and the other way around too.
8th Sep 2016, 7:26 AM
Sebastian Norr
Sebastian Norr - avatar