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?”
3
Answers
This:
doesn’t pass any values to the function. So within the function
playerSelection
andcomputerSelection
are alwaysundefined
. 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:
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):
Remove the playerSelection and computerSelection parameters in playRound() function as they are acting as local variables and not global variables. hope it helps.
Here is an introduction to how to get things working. lots of room for improvement though 😉