My code works fine, but i am getting an error that says my code should return "undefined"


#1


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


My code works correctly for multiple inputs of rock, paper, and scissors, but I keep getting this error message:

Oops, try again. Your code returned 'rock wins' instead of 'undefined' when the inputs are scissors and paper

This error message makes no sense to me.


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 (choice2 = "rock") {return "rock wins"}
    else {return "scissors wins"}
}
}
compare(userChoice, computerChoice)


#2

An else statement only takes a code to execute when previous if or else if conditions haven't been met. Also, what happened to (choice1 === "scissors")?


#3

You should also change } else if(computerChoice <= 0.67) { (less than or equal to) on line 5 to } else if(computerChoice >= 0.67) { (greater than or equal to), then change what they should evaluate to.

0 to 0.33 should be rock, 0.34 to 0.66 should be paper, and 0.67 to 1 should be scissors.

As for the error, when I ran this, if I chose scissors and the computer chose paper, it returns 'rock wins!'.

I think the error is this last else statement,
else {
if (choice2 = 'rock') {return 'rock wins'}
else {return 'scissors wins'}
}

You're not comparing choice2 to 'rock' here. Also, you don't need to compare to rock here. It should be compared to scissors. So try adding in another else if for 'scissors', and use the last else to handle cases where the user didn't input any valid choice.
else if (choice1 == 'scissors') {
if (choice2 == 'paper') {return 'scissors wins';}
else {return 'rock wins';}
} else {
return 'That wasn\'t an option.';
}


#4

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