ndrw
ndrw

Reputation: 77

Console log outputting the entire function instead of what's being returned

I'm just starting to learn JavaScript and decided to make a Rock-Paper-Scissors game with the limited knowledge I've gained so far. However, I cannot figure out why it outputs

I chose function (userChoice)
    {
        if(userChoice==="Rock")
            return "Paper";

        if(userChoice==="Paper")
            return "Scissors";

        if(userChoice==="Scissors")
            return "Rock";
    }. I win noob.

rather than just "I chose Rock. I win noob."

Here's my code:

var main = function()
{
    var yesno = confirm("Would you like to play Rock-Paper-Scissors?");

    if(yesno === false)
        return "You're lame.";

    var userChoice = prompt("Rock, Paper, or Scissors?");

    var cheat = function(userChoice)
    {
        if(userChoice==="Rock")
            return "Paper";

        if(userChoice==="Paper")
            return "Scissors";

        if(userChoice==="Scissors")
            return "Rock";
    };

    return "I chose " + cheat + ". I win noob.";
};

console.log(main());

I found that it works by moving the cheat function outside and above the main function and adjusting some things, the code works as intended. I just cannot figure out why one method works while the other doesn't.

Upvotes: 4

Views: 2991

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328760

You forgot the ():

return "I chose " + cheat(userChoice) + ". I win noob.";

With the parentheses, JavaScript will insert the function in the string instead of calling it and inserting the result.

Upvotes: 4

Kelly J Andrews
Kelly J Andrews

Reputation: 5111

You need to pass cheat as a function -

return "I chose " + cheat(userChoice) + ". I win noob.";

You have to pass in userChoice again, since the function(userChoice) call is asking for a variable, and calling it userChoice. It is not, however, actually using the previously established userChoice variable.

Upvotes: 0

Related Questions