Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR in ternary operator, using &&

Using the traditional if statement I can do this:

if(a===0 || b===0) {console.log('aloha amigo')};

But when I try to do something the same thing with a ternary operator, like this:

a===0 || b===0 && console.log('aloha amigo')

I just get errors about unexpected ||.

According to this answer: Precedence: Logical or vs. Ternary operator, we can do it using

condition1 || condition2 ? do if true : do if false

(Sorry I'm not sure how to call the ? : symbols in this case), but I'm not sure how to get it running using && (It means only run the code if returned true).

I created a codepen to test it easily. Here's the whole code:

var a = 0;
var b = 1;

a===0 || b===0 ? console.log('Works here') : console.log('And here');

a===0 || b===0 && console.log('Doesn\'t work here');

a===0 && console.log('The && works for a single test');

Here's the link

like image 320
Alex Ironside Avatar asked Jul 06 '18 09:07

Alex Ironside


1 Answers

Just take parenthesis to prevent operator precedence of && over ||

(a === 0 || b === 0) && console.log('aloha amigo')

Without parenthesis, you get (now with to show the precedence) a different result.

a === 0 || (b === 0 && console.log('aloha amigo'))
^^^^^^^                                             first evaluation
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  second evaluation
like image 66
Nina Scholz Avatar answered Oct 06 '22 01:10

Nina Scholz