Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Return and if/else

Tags:

javascript

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);
like image 263
Asim Mahar Avatar asked Sep 09 '26 19:09

Asim Mahar


2 Answers

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:

  • Remove the parameter from the function, so that computerChoice refers to the global variable. Currently the parameter shadows the outer variable with the same name.
  • (better) Call the function with an argument.

Learn more about functions.

like image 174
Felix Kling Avatar answered Sep 12 '26 09:09

Felix Kling


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/

like image 33
Reinstate Monica Cellio Avatar answered Sep 12 '26 09:09

Reinstate Monica Cellio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!