I wanted to try using the !== conditional. Why does this code log ‘Invalid choice’ and undefined?
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput !== 'rock' || userInput !== 'paper' || userInput !== 'scissors') {
console.log('Invalid choice');
} else {
return userInput;
}
};
console.log(getUserChoice('paper'));
I wanted to try the !== instead of === if statement for a rock paper scissors game. Is the issue syntax or logic?
>Solution :
This condition will always be true, regardless of the value of userInput:
userInput !== 'rock' || userInput !== 'paper' || userInput !== 'scissors'
You want to use && instead of ||, like this:
userInput !== 'rock' && userInput !== 'paper' && userInput !== 'scissors'
That way, you’ll only see Invalid choice if userInput isn’t one of the three allowed values.
Lastly, you’re seeing undefined because you’re logging the output of getUserChoice, but getUserChoice doesn’t return anything when the if statement is hit.