Home > Back-end >  if else problem...why the console didnt print string 'error' but it printed 'Randommm
if else problem...why the console didnt print string 'error' but it printed 'Randommm

Time:10-21

Nice to meet you all. I am new to programming here....my question is why the console didnt print string 'error' but it printed 'Randommm' instead? since it did not pass the first statement

const getUserChoice = (userInput) => {
      userInput = userInput.toLowerCase();
      if (userInput === "rock" || "scissors" || "paper" || "bomb") {
        return userInput;
      } else {
        console.log("Error");
      }
    };
    
    getUserChoice("Randommm"); //output:'nothing comes out instead of 'Error'

console.log(getUserChoice('rocK')) //output :rock (works fine)

CodePudding user response:

Your if statement isn't making a comparison in the 2nd,3rd and 4th conditions. You have to explicitly state what to compare against. You could do something like:

(userInput === "rock" || userInput === "scissors" ||userInput === "paper" || userInput === "bomb")

But i suggest you lift the words out to an array and do a comparison if the userinput exists within the array.

const choices = ["rock", "scissors", "paper", "bomb"];

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (choices.includes(userInput)) {
    return userInput;
  } else {
    console.log("Error");
  }
};

console.log(getUserChoice("Randommm")); //output:'Error' instead of 'Randommm'
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related