-1

This function prompts the user to pick either rock, paper, or scissors and changes the input to lowercase. If the user doesn't pick one of the above, the If statement is returned. But if the right choice is picked, the else statement is returned.

However, the else statement doesn't run if the user inputs an appropriate response.

function player() {
    let pick = prompt("Rock, paper, or scissors?");
    pick = pick.toLowerCase();

    if ((pick !== 'rock') || (pick !== 'paper') || (pick !== 'scissors')) {
        return `Please pick a valid choice ${pick}`;
    } else {
        return pick;
    }
}

If I input something other than rock/paper/scissors, I expect the if statement to run. But if I input rock/paper/scissors, I expect the else statement to run.

However, the else statement never runs, no matter what.

00Saad
  • 119
  • 8

1 Answers1

2

Use && instead of ||, otherwise the condition there will always be true. But even better, you can make the code clearer by putting the valid choices in an array and using includes:

const validPicks = ['rock', 'paper', 'scissors'];
function player() {
  const pick = prompt("Rock, paper, or scissors?").toLowerCase();
  if (!validPicks.includes(pick)) {
    return `Please pick a valid choice ${pick}`;
  } else {
    return pick;
  }
}
console.log(player());
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
  • Using **&&** definitely worked. Is that some JS specific thing, that I need to use && in a case like this, or does it apply to other languages? Using an array is a great idea, it was suggested to me earlier today when I was having trouble with another function (related to this program, lol), but I don't typically use arrays so I have to familiarize myself. – 00Saad May 15 '18 at 03:59
  • No, it's not Javascript specific, it's just plain logic. Consider `if ((pick !== 'rock') || (pick !== 'paper'))` in the case that `pick` is `'rock'`. Then, that expression reduces to `if (false || true)` which resolves to `true`. – CertainPerformance May 15 '18 at 04:00