Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rock Paper Scissors and the !== comparison

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading