Tim
Tim

Reputation: 375

Javascript: Unexpected token else

I'm using CodeAcademy, and I'm making a rock, paper, scissors game. It keeps saying I have a syntax error due to an "Unexpected token else". Take a look at my code:

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

  }
  }
 }
}

Upvotes: 2

Views: 3734

Answers (3)

Douglas
Douglas

Reputation: 37761

You have an if block which looks like this:

       if (choice2 === "scissors") {
          ...
       } else {
          ...
       } else if (choice1 === "paper") {
          ...
       }

else if can only come before an else, not after.

Using consistent indentation will make this sort of problem clearer, here is the code after running it through the formatter at http://jsbeautifier.org/

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

Here it is again, formatted so that the choice1 === lines are all at the function level, which seems to make it easier to see the structure and reduces nesting.

var compare = function(choice1, choice2) {

    if (choice1 === choice2) {
        return "The result is a tie!";
    }

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

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

Upvotes: 3

Am_I_Helpful
Am_I_Helpful

Reputation: 19168

You used a parentheses with return statement at return ("paper wins!");. Please remove the ().

Also,you have a wrong number of parentheses aligned before first else-if and second else-if.

Please close first else-if with a curly-bracket} and delete one excess from the bottom. That's the main cause of error!

Upvotes: 1

Ashalynd
Ashalynd

Reputation: 12573

You seem to have wrong number of curly parentheses.

Upvotes: 0

Related Questions