Computer Choice if/elseif/else inside a function not returning function


#1

When I run this code it prints the random "var" but under that just gives the word [Function] in brackets

var userChoice = prompt("Do you choose rock, paper or scissors?")
var random = Math.random()
console.log(random);
var computerChoice = function(random){
if(random <= .33){return "rock"}

else if(random <= .66){return "paper"}

else{return "scissors"};
};

console.log(computerChoice)

`


#2

Well computerChoice is a function that is why you see [Function] when you console.log computerChoice. What you probably had in mind was to call the function and print the result:

console.log(computerChoice(random));

Also keep in mind that the game expects computerChoice to be the choice that the computer made so better name your function something else :slight_smile:


#3

can you please let me what is wrong with this code as i could not find it.
var userChoice=prompt( "Do you choose rock, paper or scissors?");
var computerChoice=Math.random();
console.log(computerChoice);
if (0<=computerChoice=>0.33)
{
return rock;
}
else if (0.34<=computerChoice=>0.66)
{
return Paper;
}
else(0<=computerChoice=<1)
{
return Scissors;
}
var choice=computerChoice;
{
console.log(choice);
}


#4

Unfortunately this won't work:
0<=computerChoice=>0.33
it is interpreter like this:

0<=computerChoice -> true/false (1/0)
true/false =>0.33
1/0 =>0.33
false/true

So better go the long way and use && (and) to chain the two options or think deeply if you even need both :slight_smile:

return rock;

return is only allowed in functions.

rock

rock, Paper and Scissors without '' or "" are treated as undefined variables.

And last but not least why do you introduce that choice variable in the end?


#5

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