Translate expression from ternary to logical operators

Viewed 74

I wrote the following conditional statement using ternary operators:

form?.label ? (isRequired ? (form.label) : customMessage) : isRequired ? ' ' : customMessage

How do I write this line using logical operators only?

1 Answers

First, note that your code is equivalent to:

isRequired ? (form.label ? form.label : ' ') : customMessage

which is slightly more efficient because it doesn't test form.label if isRequired is false.

Now, form.label ? form.label : ' ' means we want form.label, or if it is false, something else. This can be written with the lazy logical or operator: form.label || ' '.

So we get:

isRequired ? (form.label || ' ') : customMessage

In general, c ? a : b is equivalent to (c && a) || b if a is guaranteed to always be true. This works because the two logical operator are lazy: if c is false, then a is not evaluated because c && a cannot be true regardless of b; if c is true, then c && a is also true, so b is not evaluated because the whole conditional expression must be true regardless of b.

In our case, (form.label || ' ') is guaranteed to be true, because ' ' is true. So finally your expression becomes:

(isRequired && (form.label || ' ')) || customMessage
Related