For formatting code in forum posts, see [How to] Format code in posts
Here are a few issues to consider:
determineWinner(userChoice, computerChoice);
console.log(determineWinner());
You pass arguments to the determineWinner
function, but then don’t do anything with the returned string. You should either assign the returned string to a variable OR just print the returned string immediately without assigning it to a variable. In its current form, you aren’t doing anything meaningful with the returned string. You are just discarding it. In the next statement i.e. console.log(determineWinner());
, you are making a fresh function call with no arguments which causes undefined
to be assigned to both parameters of the determineWinner
function. You can do:
// Save returned string to a variable
let result = determineWinner(userChoice, computerChoice);
console.log(result);
// OR
// Print it directly without assigning to a variable
console.log(determineWinner(userChoice, computerChoice));
- Since, the
playGame
function prints the result to the console instead of returning it, so consider changing:
// You wrote:
console.log(playGame());
// Change it to:
playGame();
- In its current form, your program doesn’t function as intended. You wrote:
if (userChoice === computerChoice) {
return 'The game is a tie.';
}
if (userChoice === 'rock' && computerChoice === 'paper') {
return 'Sorry, but you lost. =('
} else {
return 'Congratulations! You won!'
}
if (userChoice === 'paper' && computerChoice === 'scissors') {
Suppose userChoice
is 'paper'
, you won’t reach the correct block. If userChoice
is 'paper'
and computerChoice
is 'paper'
, then you will return 'The game is a tie.'
which is correct. But, if userChoice
is 'paper'
and computerChoice
is something other than 'paper'
, your program will always return 'Congratulations! You won!'
That is because
if (userChoice === 'rock' && computerChoice === 'paper') {
will evaluate as false
and then you will return the string from the else
block.
Instead, there are a couple of ways you can rectify this.
One Approach:
if (userChoice === computerChoice) {
return 'The game is a tie.';
}
if (userChoice === 'rock' && computerChoice === 'paper') {
return 'Sorry, but you lost. =('
} else if (userChoice === 'rock' && computerChoice === 'scissors') {
return 'Congratulations! You won!'
}
if (userChoice === 'paper' && computerChoice === 'scissors') {
Another Approach:
if (userChoice === computerChoice) {
return 'The game is a tie.';
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'Sorry, but you lost. =('
} else {
return 'Congratulations! You won!'
}
}
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
// ...