For vs While Loops

For vs While Loops
0.0 0

#1

I am trying to understand use cases for each type of loop. I was recently working on the Profile Lookup challenge, and had everything correct, but was using a While loop. The While loop got me an answer of “No such contact” everytime - the basic catch-all return value at the end of the function - no matter what variables where fed in. When I went to research, I found that the answer involved a for loop. So, I switched my while loop to a for loop and it worked. Without picking apart the program, I would like to know if there are specific use cases for each, as they seem like very similar looping to me (though a for loop seems to be more efficient).

I guess I am asking if there’s a fundamental difference between the loops that would cause someone to use one over the other in different situations.

Thank you so much to this community! I couldn’t do this without you!


#2

Usually, for loops are used when you know how many iterations you need to do, example: a fixed number, size of a list or array, length of a string.

While loops are usually used when you don’t know beforehand how many times you need to loop/process something, but you know the condition when your loop should end, for example: end of file condition, end of records dataset, a match is found, a condition is true (or not true).


#3

They’re semantically identical, but people tend to use them as owel explained. Sometimes you just don’t need to know the loop iteration index, so a while loop is cleaner.

These two basic uses are identical:

for (let i=0; i < somelimit; i++) { console.log(i); }

let i=0;
while (i < somelimit) { console.log(i); i++; }

So in your example you hadn’t just changed the looping variant, you also changed the logic.


#4

So, those two are essentially the same, it’s just that one is typically used when you don’t have a known number of iterations. So, somehow my while loop was logically different than what my for loop ended up being. Seems like the logic is clearer in a for loop (all in one line). I am guessing that my positioning of the i++ statement was probably in the wrong place (once I get to about 4-5 closing brackets in a row I tend to get lost as to which bracket goes where). I probably should have copied it from FCC to something like Atom so that I can see the brackets better.

Thank you so much for the help! It’s clearer now what happened when I changed to the for loop.


#5

You will almost always use for loops. I find it to be very rare that you would need/want to use a while loop. One example of a good use of a while loop is when making games.

while( !done ){ 
 update_inputs();
 draw_game();
//ect...
}