Search code examples
javascriptarraysfunctionconsole.log

Need Assistance with a JavaScript Function for the "Paper, Rock, Sissors Challenge."


I am testing my playRound() function and not receiving the desired results with a console.log output. The output is always the initial return of the if statement.

I have initialized the global variable of playerChoice to equal a string, i.e. “rock”.

I have verified that the output of the getComputerChoice() functions generates a random selection from the array, .i.e. paper, rock or scissors, with console.log(getComputerChoice()).

However, when I call the playRound() function I only receive the initial return on the if statement of “It’s a tie”.

const playerSelection = "rock"
const computerSelection = getComputerChoice();
console.log(playRound());

function getComputerChoice() {
    const choice = ["paper", "rock", "sissors"];
    return choice[Math.floor(Math.random() * 3)];
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === computerSelection) {
        return "It is a tie!";
    }   else {
        return "Please try again!";
    }
}

Why does the code seem to short circuit at the initial return of the if statement and never proceed to outputting “Try Again?”

console.log(getComputerChoice()) console.log(playRound())


Solution

  • This:

    playRound()
    

    doesn't pass any values to the function. So within the function playerSelection and computerSelection are always undefined. Within that function you are declaring those two local variables with the same name as two global variables. The local variables shadow those global variables, so you can only use the local ones.

    If you meant to use the global variables, don't re-declare local variables of the same name:

    const playerSelection = "rock"
    const computerSelection = getComputerChoice();
    console.log(playRound());
    
    function getComputerChoice() {
        const choice = ["paper", "rock", "sissors"];
        return choice[Math.floor(Math.random() * 3)];
    }
    
    function playRound() {
        if (playerSelection === computerSelection) {
            return "It is a tie!";
        }   else {
            return "Please try again!";
        }
    }

    Alternatively, if you do want to use local variables in that function, pass your values to it (and I recommend giving them different names to avoid confusion):

    const playerSelection = "rock"
    const computerSelection = getComputerChoice();
    console.log(playRound(playerSelection, computerSelection));
    
    function getComputerChoice() {
        const choice = ["paper", "rock", "sissors"];
        return choice[Math.floor(Math.random() * 3)];
    }
    
    function playRound(pl, cmp) {
        if (pl === cmp) {
            return "It is a tie!";
        }   else {
            return "Please try again!";
        }
    }