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?
CodePudding user response:
The issue is with the =
vs ===
operator.
===
is used to check for equality, and =
is for assignment.
When you write
if(userInput = 'rock')
it means userInput
is assigned the value of rock
.
What you really want is if(userInput === 'rock')
Regarding the ||
operator (also called OR), what happens is a short-circuit operation. If you write A || B || C
, the below happens:
- A is evaluated. If value is
true
, B and C are not evaluated. - If A is
false
, then B isevaluated
. - If
B
is true, thenC
is not evaluated. - Otherwise, C is evaluated and value of C is returned.
CodePudding user response:
There is no functional difference between using ||
and using if
/else
.
In JavaScript, the ||
operator works like this:
For a || b
, check if a
is truthy. If yes, resolve to a
. Otherwise, resolve to b
.
Now, as you may have noticed, the wording of that is pretty much identical to how you would describe the behavour of an if
/else
conditional block. Functionally, there is no difference in behaviour.
On a related note, the &&
operator works in a similar way, except then only if a
is truthy will a && b
resolve to b
. If you ever look at minified code, you will sometimes see &&
used to replace an if
statement, because a && b
is functionally identical to if (a) { b; }
but takes up fewer characters.
I wouldn't recommend using that approach in un-minified code, since it's definitely harder to follow, but it does take up fewer characters without functioning differently, which is why it's used by minifiers. Kind of similar to how they often use !0
instead of true
.
CodePudding user response:
The difference is that the if else statement is only checked/run if the previous if/if elses are false. The or (||
) statement is true if any of the single conditions are true