function always returning last if statetment value [duplicate]
Solution 1:
Your problem here is that you are mixing cases. You set computerChoice
to either "rock"
, "paper"
, or "scissors"
but then inside of the function you are performing comparisons with "Rock"
, "Paper"
, or "Scissors"
.
Just use lowercase throughout, and add userChoice = userChoice.toLowerCase()
after the prompt()
call.
Solution 2:
jsFiddle
No return
s needed.
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";
}
function compare(choice1, choice2) {
if (choice1 === choice2) {
alert("The result is a tie!");
}
if (choice1 === "Rock") {
if (choice2 === "Scissors") {
alert("Rock wins!");
} else if (choice2 === "Paper") {
alert("Paper wins!");
}
} else if (choice1 === "Scissors") {
if (choice2 === "Rock") {
alert("Rock wins!");
} else if (choice2 === "Paper") {
alert("Schissors wins!");
}
}
};
compare(userChoice, computerChoice);