Console says "undefined"...*insert but why meme here*


#1


if i want to output console.log(......)the last line in the console says "undefined" but i dont know why? the line should be empty. i forgot to mention: if i enter a valid choice (paper, rock, scissors), the code works just fine ...and the console.log is correct. but if my first choice was something thats not defined, and i get asked to enter a valid value--> thats when i get the undefined message.


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 picked: " + 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(choice2 === "paper"){
        return "scissors WINS"
    }else{
        return "rock WINS"
        }
    }
    if(userChoice == "rock", "paper", "scissors"){
        confirm("Your choice is invalid")
        var newChoice = prompt("Choose rock, paper or scissors?");
        console.log(compare(newChoice, choice2));
    }
  };
 console.log(compare(userChoice, computerChoice));

Thanks for your responses.


#2

because you make a recursive function call ( a function call inside a function), you do this here:

console.log(compare(newChoice, choice2));

however, the result of this function call doesn't get returned, causing a undefined, use return instead:

return compare(newChoice, choice2);

#3

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