If or Else infinite loops


#1

https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/3?curriculum_id=506324b3a7dffd00020bf661#

browser crashes because of infinite loop



var number1 = true;
var numberoftries = 0;
var number2=Math.floor(Math.random()*2);
while(number1===true){
    if (number2===true){
        console.log("heads try again");
        numberoftries++;
    }
    else if (number2===false){
     console.log("tails, you win, it took you  " + numberoftries + " "+"tries");
     number1 = false;
    }
}



#2

I can’t find any errors, please help


#3

You have this

in the wrong position. See corrected.

var number1 = true;
var numberoftries = 0;
var number2=Math.floor(Math.random()*2);;
while(number1===true){
    if (number2===true){
        console.log("heads try again");
        numberoftries++;
    }
    else if (number2===false){
     console.log("tails, you win, it took you  " + numberoftries + " "+"tries");
    }
    number1 = false;
}

#4

ok, thanks! but shouldn’t it change it to false if the random number is false? Thanks for everything!


#5

Yes, it does change to false. To log that to your console, consider my review below.

var number1 = true;
var numberoftries = 0;
var number2=Math.floor(Math.random()*2);
while(number1===true){
    if (number2===true){
        console.log("heads try again");
        numberoftries++;
    }
    else if (number2===false){
     console.log("tails, you win, it took you  " + numberoftries + " "+"tries");
    }
    number1 = false;
    console.log(number1);
}

I hope this helps! :smile:


#6

Yes it does, thank you!


#7

You’re welcome. Have fun coding!


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.