最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - OR in ternary operator, using && - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Jul 6, 2018 at 9:00 Alex IronsideAlex Ironside 5,04914 gold badges73 silver badges134 bronze badges 1
  • "But when I try to do something the same thing with a ternary operator..." That's not a ternary operator (an operator accepting three operands). That's two binary operators (|| and && -- operators accepting two operands). JavaScript currently has only one ternary operator: The conditional operator: condition ? ifTrue : ifFalse. It could have another ternary added at some stage, but for now it has only one. – T.J. Crowder Commented Jul 6, 2018 at 9:04
Add a comment  | 

1 Answer 1

Reset to default 15

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
发布评论

评论列表(0)

  1. 暂无评论