For the following code, I keep getting Scissors back for alert. I am not sure what am I doing wrong here.
var computerChoice = Math.random();
var newChoice = function (computerChoice) {
if (computerChoice <= 0.34) {
var newChoice = "rock";
return newChoice;
} else if ((computerChoice >= 0.35) && (computerChoice <= 0.66)) {
var newChoice = "paper";
return newChoice;
} else {
var newChoice = "scissors";
return newChoice;
}
}
var newerChoice = newChoice();
alert(newerChoice);
You are not passing an argument to newChoice when you call it, hence the value of the parameter computerChoice is undefined. undefined <= 0.34 is false, same for the other comparisons.
Two possible solutions are:
computerChoice refers to the global variable. Currently the parameter shadows the outer variable with the same name.Learn more about functions.
There appears to be a bit of confusion over variables and parameters. Here's some working code...
var newChoice = function (choice) {
if (choice <= 0.34) {
return "rock";
} else if (choice <= 0.66) {
return "paper";
} else {
return "scissors";
}
};
var computerChoice = Math.random();
var newerChoice = newChoice(computerChoice);
alert(newerChoice);
The value that is passed into newChoice is the parameter choice. I trimmed out the && as they're not required. If choice is not <= 0.34 then it must be greater than 0.34, so that check is not required later.
computerChoice is a random value variable that is passed as a parameter to the function.
Here's a working fiddle example...
http://jsfiddle.net/ArchersFiddle/0dfhoa63/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With