What if choice 1 is scissors - undifined help


#1

Good Morning all,

Having an issue with my code where I'm getting the following error message returned:
"Oops try again. Your code returned 'rock wins' instead of 'undefined' when the inputs are scissors and paper"

my code is as follows:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
	computerChoice = "rock";
} else if(computerChoice <= 0.67) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
} console.log("Computer: " + computerChoice);


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";
        }
    }
    
    else if(choice1 === "scissors") {
        if(choice1 === "paper") {
            return "scissors wins";
        }
        else {
            return "rock wins";
        }
    }
}

Any ideas?


#2

Well the error message says that the problem occurs when using scissors vs paper. Now if we have a look at the code we see that with this input we end up here:

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

And here is the problem

 if(choice1 === "paper") {

as choice1 is obviously scissors when you come to this case you'll always pick the else path which leads to the interesting result that for scissors vs paper -> rock wins. So instead of choice1 better use choice2 for your inner if.


#3

Yup, that was a silly mistake to make! Thanks for the speedy advise though.


#4

A post was split to a new topic: Getting the same "undefined" message