I am doin everything right but it says syntax error


#1

I am stuck on 7. What if choice1 is paper.

This is my code and I don't know what I am doing wrong.

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";
}
else {
return "scissors win";
}
}
};

In the console box it displays "SyntaxError: Syntax error" which makes no sense to me, but it might be because I am new at this. If anyone knows what's wrong please tell me. Thanks in advance for helping.


#2

Hi @11dstav,

Please see the code sample below, I simply indented it to help with viewing where the error occurs.
In short the error for syntax is most likely due to the way you constructed the else if statement, as it follows an else statement, but as you probably know now you saw this, else should be last, though in this case you probably just want to move the else up into the code block as below. :wink:

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 { //moved this up into here
            return "paper wins";
        }
    }
    else if(choice1 === "paper") { //error is here where you have the else if after an else, unless you move the else up as shown above
        if(choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors win";
        }
    }
};

#3

Thank you so much @mike_in_training. This really helped


#4

It says syntax error: unexpected keyword 'else'.. Do not understand where I am going wrong with my code, can anyone please assist!! Thank you :smile:
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";
}
else {
return "scissors wins";
}
}


#5

If you give your code some format you could see it much easier. No changes applied but format:

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";
    } else {
        return "scissors wins";
    }
}

As you can see the function is closed early which lead to the problems. The second else if is actually how it should look like but now it is outside of the function.