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
3,416 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.

adam n
adam n
57,280 Points

I like this answer:

https://stackoverflow.com/a/6710639

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

Thank u

adam n
adam n
57,280 Points

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