1

I got an interesting warning message from IntelliJ about some JavaScript code:

((a === 'foo') || (a === 'bar')) ? true : false' can be simplified to '!!(((a === 'foo') || (a === 'bar')))

I see why the structure condition ? true : false doesn't make sense, but shouldn't the condition itself represent a boolean value? So why should I use the double negation for the whole expression?

ytg
  • 1,755
  • 2
  • 23
  • 41
  • 1
    I assume you are asking why the IntelliJ produced such "simplification" suggestion? – CppLearner Feb 18 '14 at 07:43
  • 2
    I assume IntelliJ only recognizes the `cond ? true : false` part, but doesn't actually know what `cond` returns. That's why it adds `!!` as a precaution. But you are right, it is not necessary here. – Felix Kling Feb 18 '14 at 07:44
  • Ask yourself this: Do you _really_ need it to be a boolean value that's returned? Isn't a "truthy" good enough? – Cerbrus Feb 18 '14 at 07:44

2 Answers2

3

Ask yourself this: Do you really need it to be a boolean value that's returned?

To answer your question: the reason IntelliJ suggests it, is because that's how it is configured.
It's just one of the ways you can have IntelliJ handle pointless conditionals.

In the IntelliJ intentions documentation, Look for: JavaScript --> Conditional Operator --> Remove Pointless Conditional.

A double boolean negation (!!) is a shorter, and arguably cleaner way of casting the result of the statement to a boolean value, instead of the truthy or falsy the statement normally returns.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • We should be explicit **when we specifically want a boolean** and use `Boolean(a || b)`, leaving the `!!` trick to Uglifying libraries. Proof that `!!` is unclear at first sight is the fact that there is a [really popular question on Stack Overflow about it](https://stackoverflow.com/q/784929/1218980). – Emile Bergeron Apr 02 '19 at 17:19
0

You could test a Regular Expression: /^foo$|^bar$/i.test(a). Now you don't need the ternary also.

!! converts the expression to a Boolean. It's to make sure you always get a Boolean from it. If you're certain the expression will deliver something 'truthy/falsy' I'd say you can do without the conversion. If you use the Regular Expression above the conversion is definitely not necessary.

KooiInc
  • 119,216
  • 31
  • 141
  • 177