7. Unexpected token else


#1


https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/1/3?curriculum_id=506324b3a7dffd00020bf661#

Unexpected else, bracket problems? I cant see the error


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"}
};


#2

Hello there @natemunoz9806! I'm hoping to help you out here. You're pretty smart since you realised it was probably a brace error... and you're right! So, what's happening here is that you've accidentally closed the

else if (choice1= "rock") {

by having two braces after

return "rock wins"

This is incorrect because you want to call an "else" to follow the "if" that lies within that else if (choice1= "rock").

Try to notice the difference between the code you supplied and the following. Go brace by brace if needed:

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" ; 
    }
};

NOTE: Also, don't forget to end lines with ; when appropriate. For example, you didn't have them after two of your return statements.

Hope that helps you out. Keep up the good luck and don't hesitate to ask for more help if you need it (you can even call me to the thread using the @silasmao tag. I might not be able to help since I'm also learning, but I'll at least check it out if I can! :wink: )

-- silasmao


#3

You have:

if
else if
else               <- this one shouldn't be here
else if
else

The else statement that's out of place belongs to a nested if-statement. A simple case of placing the closing bracket a little bit too early.


#4

Thank you! Haha I was looking at it over and over, and could not make it out for the life of me. Your response was extremely helpful and I made the correct changes. :slight_smile:


#5

2 posts were split to a new topic: I am getting an error that says "SyntaxError: Unexpected token else


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.