6. What am I doing wrong here?


#1


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


SyntaxError: expected expression, got keyword '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";
}

}


#2

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

It's necessary to do spaces for all else statements because you can check where you need put { } to close it.


#3

I recommend that everyone take their code offline when doing something complex and when errors occur that aren't obvious in the Codecademy console. An editor will highlight errors in your code's syntax, which Codecademy will not.

A good example is that when your curly braces aren't correct the editor will indicate this, typically with a squiggle underline (just like in a word processor). Here is a screen shot:

showing how the addition of a curly brace in the wrong place makes the function's end brace incorrect. I've highlighted where the extra brace was added in the upper part of the image code. The great thing is that the editor will highlight the other brace in the pair, which makes it easier to see the pairs in your code. Especially useful for nested functions and Closures.

Going offline enables you to play with your solution and experiment with other ways of doing it. You can refactor as much as you want and can save it all to your cloud storage and then to Git for a history. I've just completed the Rock Paper Scissors program and have refactored it many times. Each time applying something new. My next refactor will likely be to take it from being an imperative solution (if else) to a declarative solution (using functional programming keywords like map, filter and reduce). Easy to do if you have gone offline to explore for a while.

This editor is Visual Studio Code. It's free, fast and stable, and has loads of extensions for when we eventually need them. Just use it as a simple text editor and don't worry about doing too much else for starters.


#4

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