29

What are the benefits of using a while loop over a for loop? When I'm iterating through arrays, I always use a for loop so I wondered if I'm missing something here.

I've never had a situation where a for loop doesn't do the job, but I'm worried that I may be picking up bad habits here. My usage of loops has been with regards to elements on web pages, stuff in animations, etc..

3 Answers 3

53

These are the reasons I would choose one over the other:

For-loop Syntax:

for( int i = 0; i < 10; i++)
{
    //Some code here
}

I would use a for loop for the reason that I may KNOW the NUMBER OF ITERATIONS I need to do and I have an INCREMENTING variable which can be handy sometimes.

While-loop Syntax:

while(!done)
{
    //Some code goes here
}

I would use this loop when I am NOT SURE how many ITERATIONS I might need to carry out. Examples: Waiting for user to input correct input values and keep looping until he/she inputs the proper value.

Do-While loop Syntax:

do
{
    //Some code here
}
while(!done);

This loop is almost the same as a while-loop but I would prefer this when I need something done ATLEAST ONCE before I start verifying whatever it is that would make me wanna loop and do that code again. Example: ask a user for an input for the first time and then validate it. If wrong input given then loop back and ask for input again

2
  • 1
    I know this post is old I felt i had to. A for loop can also be used like a while loop, exp: for(;!done;) { // do stuff } for loops are multi-use and better in most situations in comparison to a while loop, in terms of performance they also tend to be faster (but this is not applicable to js), while loops are the type that should only be used when absolutely necessary, a lot of programmers out there tend to use them all over the script. My advice is stick to for and do-while loops, only use while loops when you're presented with a case where the other 2 cannot be used.
    – Bargros
    May 16, 2018 at 10:25
  • Just want to say that setInterval() and clearInterval() are what I use for waiting on user input. This way you can control how fast the loop is rather than the loops being unthrottled and full speed. I may use the while loop as described in this fashion to iterate through building a string from changing array/s so that there is a definite and not so drawn out end in the while loop.
    – JSG
    Sep 6, 2019 at 3:23
15

Functionally, one can substitute the other in all conditions. Is one better than the other? Not in javascript (which you have tagged) as its not a compiled language.

But in languages like C++, a for loop usually gives the compiler a static count to loop which the compiler can use to optimize the binary. So it should run faster (on very large loop counts).

That should not be a worry in today's age where you won't even notice the performance increase on a loop running for 10000 iterations on a 2.5 ghz quad core CPU.

However, personally, aesthetics matter to me (and it should to you if you are serious about the art of coding) a lot. For example when you are dealing with an external condition (the variable you are checking is defined outside the loop), go with a while loop. Its just semantically so much beautiful. Also while loop should be the de-facto choice for an infinite loop (I don't see a reason why you would have an infinite loop in javascript, though).

In short, follow the syntax. Are you just checking a condition? Go with a while loop. Are you initializing and incrementing/decrementing something with in the context of a loop along with checking a condition? Only then go with the for loop.

3
  • I like the last statement, on the point. Nov 2, 2017 at 12:20
  • "I don't see a reason why you would have an infinite loop in javascript, though." You would need it when you are working with binary, quad, or oct tree data structure.
    – martian17
    Dec 31, 2018 at 3:02
  • infinite loops can be useful when dealing with an array with a changing number of elements, where you can break the loop when you get the right type of response, or your array goes empty. example: if your using value += array.shift(); and waiting for a pattern in value Dec 14, 2019 at 3:06
7

You can always use either of the loops. But, the most common usage of for loops is when the number of iterations are known, and the while loop having uncertain number of iterations or would depend upon a particular condition. For example:

var arr = ["a", "b", "c"];
for (let i=0; i<arr.length; i++) { // will loop 3 times (length of arr = 3)
    // do something
}

var x = "Hello";
while (x != "World") {
    // do something
    if (some_condition) {
        // do something
    }
    else x = "World";
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.