4. The first if statement - infinite loop


#1

https://www.codecademy.com/en/courses/javascript-beginner-en-mrTNH-6VIZ9/0/4?curriculum_id=506324b3a7dffd00020bf661

I am getting an infinite loop when I run the following code. I'm not sure why this is happening: at the end of the code, slaying = false, wouldn't the while loop end?


var slaying = true
var youHit = Math.floor(Math.random() * 2)
var damageThisRound = Math.floor(Math.random() * 5 + 1)
var totalDamage = 0
while (slaying) {
    if(youHit) {
        console.log("Congratulations, you hit the dragon!")
    } else {
        console.log("The dragon defeated you.")
    slaying = false
    };
};


#2

slaying will only be set to false if youHit is false, so if youHit is true, you have an infinity loop


#3

Thank you!

In this case, could I use the following code to set slaying to false?

var slaying = true
var youHit = Math.floor(Math.random() * 2)
var damageThisRound = Math.floor(Math.random() * 5 + 1)
var totalDamage = 0
while (slaying) {
    if(youHit) {
        console.log("Congratulations, you hit the dragon!")
    } else {
        console.log("The dragon defeated you.")
    };
    slaying = false
};

#4

else {
        console.log("The dragon defeated you.")
    }; // remove this semi-colon

} of else shouldn't have a semi-colon, but yes, that should do the trick


#5

Thank you for the feedback!


#6