jeudi 7 octobre 2021

What's difference in using else-if vs or in JavaScript

I was creating a rock-paper-scissor game to test my knowledge of functions. I had written this code to see whether the user had given a valid input of rock, paper or scissor:

const getUserChoice = userInput => {
 userInput =  userInput.toLowerCase();
 if(userInput === 'rock'){
   return userInput;
 } else if(userInput === 'paper') {
    return userInput;
 } else if(userInput === 'scissor'){
    return userInput;
 } else {
   console.log('Invalid Option');
 }
};

When I tested the last else statement by doing a console.log like so:

console.log(getUserChoice('water'));

It printed out rock instead of printing "Invalid Option".

When I checked the solution I saw this:

if (userInput === 'rock' || userInput === 'paper' || ... ) {
  return userInput;
} else {
  console.log('Error!');
}

So what's the difference between using an else-if to accomplish this task vs using the || operator?

Aucun commentaire:

Enregistrer un commentaire