Code academy error (confused) ^^

47 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 answers

1
Claudiu Creanga 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
TankorSmash 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.