0

I am experimenting with JavaScript conditions. In the code below, why is my first condition not returning true while the second one does?

Javascript:

   arr = [1,2,3];
        if (arr[0] !== (1 || 2)){console.log('true')}
        //undefined

        if (arr[0] !== (2 || 1)){console.log('true')}
        //true
Robert0000
  • 17
  • 5
  • what is the expected result of the above (pretending it would work this way)? – Nina Scholz Sep 05 '20 at 16:48
  • Try to run `console.log(1 || 2)` and `console.log(2 || 1)` and see what values they log. – Ivar Sep 05 '20 at 16:49
  • "A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by || (OR) operators" https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals – WOUNDEDStevenJones Sep 05 '20 at 16:50
  • A simpler way of understanding this is to just know that in any compound `if` statement each condition must be a complete condition that could be evaluated on its own. `(1 || 2)` is not a complete condition and, in this case will always evaluate to `true`. – Scott Marcus Sep 05 '20 at 16:52
  • It looks like you were actually trying to do something like: `[1,2].indexOf(arr[0])<0`. – Carsten Massmann Sep 05 '20 at 16:53

2 Answers2

2

|| will evaluate to either:

  • The first value, if it's truthy, or
  • The final value (which may be either truthy or falsey)

Since 1 is truthy, (1 || 2) evaluates to 1:

if (arr[0] !== (1 || 2)){console.log('true')}
// resolves to
if (1 !== (1 || 2)){console.log('true')} // resolves to
if (1 !== (1)){console.log('true')} // resolves to
if (1 !== 1){console.log('true')} // resolves to
if (false){console.log('true')}

So the first if statement does not go through. In the second case, 2 || 1 evaluates to the first truthy value of 2, so the if statement succeeds.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

For this, you need an array of numbers to check against and negate the check as well.

const arr = [1, 2, 3];

if (![1, 2].includes(arr[0])) {
    console.log(arr[0], 'is not', 1, 'or', 2);
}

if (![1, 2].includes(arr[2])) {
    console.log(arr[2], 'is not', 1, 'or', 2);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392