r/javaScriptStudyGroup • • Nov 25 '17

can someone explain while and infinite loops to me? I feel like I sort of get it but actually trying to write out an infinite loop is difficult. I understand the definition just not how to write it..

I'm really having trouble understanding infinite loops. Is an infinite loop the writing found inside the while loop? I'm currently in this lesson in code academy about loops and I got stuck at the while and infinite loops? I compared the while loop to a Rubik's cube because you have to go through so many answers to get the right answer. I'm not sure if that is a good comparison or not.

2 Upvotes

2 comments sorted by

2

u/Abiv23 Nov 25 '17

Write a condition that won't be met in your logic portion of the loop

Example:

let n = 1; let k = 0;

While (n > k ){ n += 2; k += 1; }

1

u/SaidWrong Nov 25 '17 edited Nov 25 '17

A while loop means "keep going through the loop while this condition I set is true". A life example could be:

While (hungry == true){

* Pick up fork
* Scoop food
* Bring to mouth
* Chew
* Swallow

If (stomach == full){
     Hungry = false
}

}

In this case, that 'if' statement at the bottom is very important. Without it, there would be no way to be anything but true. So you would execute the loop, check if hungry is true, and it is, so do the loop again and repeat forever. That's bad. You want your loop to terminate. So you need a way for your condition to turn false. Is this helpful?