Code academy error (confused) ^^

100 Views Asked by At

I would like to know why this code gives the message: SyntaxError: unexpected token else.

var compare = function(choice1,choice2){
if(choice1===choice2){
    return("The result is a tie!");
}else if(choice1==="rock"){
    if(choice2==="scissors"){
        return("rock wins");
    }else{
        return("paper wins");
    }else if(choice1==="paper"){
        if(choice2==="rock"){
            return("paper wins");
        }
    }  
}

};

2

There are 2 best solutions below

1
On BEST ANSWER

Because else if should be before else, like this:

var compare = function(choice1,choice2){
if(choice1===choice2){
    return("The result is a tie!");
}else if(choice1==="rock"){
    if(choice2==="scissors"){
        return("rock wins");
    }else if(choice1==="paper"){
        if(choice2==="rock"){
            return("paper wins");
        }
    } else{
        return("paper wins");
    } 
}
0
On

You have an else if after the else, so it's getting tripped up.

It should be

if(choice2==="scissors"){
    return("rock wins");
} else if(choice1==="paper"){
    if(choice2==="rock"){
        return("paper wins");
    }
} else{
    return("paper wins");
}

If statements always start with an if, then the else ifs, and then finally the else. Everything but the first if is optional, but the order always needs to be the same.