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?
CodePudding user response:
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.
CodePudding user response:
You are getting Invalid choice
because of Short-circuit evaluation. This means, the logical OR (||)
expression is evaluated left to right and any of the left values get truthy-value then the rest will not be evaluated.
userInput !== 'rock' || userInput !== 'paper' || userInput !== 'scissors'
When userInput
is equal to paper
and execute the above condition The first one gets truthy-vaule because paper
and rock
are not the same. So that, the rest of them will not be evaluated (userInput !== 'paper' || userInput !== 'scissors')
. That conditon become true and logged invalid choice
. And in the condition you didn't return anything so getUserChoice
function return undefined
.
CodePudding user response:
Your function is not returning anything on the truthy if path, only on the else path.
Also the inverse of if(x==="a" || x==="b" || ...)
(aka if(!(...))
) is if(x!=="a" && x!=="b" && ...)
you need to swap ||
to &&
and &&
to ||
too, not just ===
to !==
and !==
to ===
.
CodePudding user response:
This is more a logical problem. You are asking the code to check if the value submitted by the user if different from 'rock' OR is different from 'paper' OR is different from 'scissor'.
So if you try to insert a good value, like 'paper', the check will pass anyway because 'paper' is anyway different from 'rock' or 'scissor'.
In this case you may want to check if the word passed by the user is different from 'paper' AND 'rock' AND 'scissor'.