Lesson 11 infinite looping


#1

// Write your code below!
var kale = true
var soup = true

for(kale === true; kale === true; kale = false){
console.log("for worked")
}
do{
console.log("do worked")
}while(soup){
console.log("while looped")
soup = false
}

When I run this it just infinitively repeats the code in the "do" section, why is that?


#2

Look again at your usage of "=" vs "==" and "==" vs "===". I think in that answer is the solution to your problem in this bit of code. I hope this helps. Codeacademy can some times be sloppy about writing their tutorials. I ran into an issue like this which kept running an infinite loop even though I was following the directions in the tutorial. Good Luck friend!.


#3

This might even work although it is pretty weird. Would you mind to describe what you wanted to do here or is this some kind of art work?

The error is in the do while loop or better after it:

do{
    console.log("do worked")
}while(soup)

this is the do while loop and as soup is true and stays true you're trapped in an infinite loop. A do while loop is just a while loop where the loop body (the stuff in {}) comes before the condition and is therefore executed once without checking the condition. After this it is a regular while loop -> check condition jump back to do -> execute code -> check condition -> ...

So changing the value to false in a pseudo while loop:

{
    console.log("while looped")
    soup = false
}

doesn't help as this comes after the loop and as the loop never stops you'll never reach it.


#4

Ah I see, so when I change the variable it needs to be in the "do" section of the loop? Btw I literally lol'ed at,

I wanted the code to execute when kale = true and when kale was no longer true I wanted the loop to stop, although in hindsight it seems a bit clunky haha.


#5

Ah I see, so when I change the variable it needs to be in the "do" section of the loop?

Yes.

I wanted the code to execute when kale = true and when kale was no
longer true I wanted the loop to stop, although in hindsight it seems a
bit clunky haha.

As said it actually works although for(; kale === true; kale = false){ would have been sufficient. But it is honestly the first time I saw it like this :slightly_smiling: