5. The Second "if" statement


#1

var slaying=true
var youHit=Math.floor(Math.random()*2)
var damageThisRound=Math.floor(Math.random()*5+1)
var totalDamage=0
while(slaying)
{
slaying=false
if(youHit)
{
console.log("You hit the dragon!")
totalDamage+=damageThisRound
}
if(totalDamage>=4)
{
console.log("You slew the dragon!")
slaying=false
}
else
{
youHit=Math.floor(Math.random()*2)
}
else
{
console.log("The dragon deafeated you!")
slaying=false
}
}

It says unnexpected token else. Can anyone tell me what's wrong?


#2

Just remember the "else" statement is an "all encompassing" conditional. Meaning specifically anything that doesn't fit into the if statement or the "else if" statement has already covered. So you can't have two "else" statements at the same time to one if statement, that's saying:

"If this happens, then I want to do this. Or else I want to do this.. or else I want to do this........"

It doesn't make sense, and confuses the console.


#3

I had the same Error, just format your code a bit and it should become correct
Here is mine

var slaying=true
youHit = Math.floor(Math.random()*2);
var damageThisRound = Math.floor(Math.random()*5 + 1)
var totalDamage = 0
while(slaying) {
    if (youHit) {
        console.log("You hit!");
        totalDamage=+damageThisRound
        if (totalDamage>=4) {
            console.log("Dragon has croaked, congrats you just killed more wildlife, your ansestors must be pround with you for making another species extinct!");
            slaying=false;
        }else{
            youHit=Math.floor(Math.random()*2);
        }
    } else {
        console.log("You missed!");
    }
    slaying = false;
    
}

#4

A bit of grammatical errors sorry.
:blush: