Like many languages, JavaScript has the conditional (ternary) operator. What's wonderful about this operator is that it can be nested in expressions and it returns a value.
So what is the right way to use it in JavaScript?
Should we try to avoid it?
While writing code I found something that can replace ternary operator under certain conditions.
Traditional use:
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? flase : true;
What I found was:
const foo = a || b;
const bar = !!c;
const baz = !c;
There is one more, &&
(AND) operation.
const boo = a `&&` 'Hello';
Here the AND operator will short-circuit if the left operand is false, it acts identically to the first part of the ternary operator.
Do you know more? Please do let me know in the comments.
Top comments (4)
Be careful with using && for fallbacks, since you need to keep in mind what counts as a falsy value in JavaScript (that includes e.g. an empty string or empty array, while you might have written the code with the expectation of getting either a (non-empty) array or null).
ES2020 now has the nullish coalescing operator
??
. If the left operand is null or undefined, the right hand operand is used, if it’s not, then the leftYou can also use Boolean(val) instead of !!val. It may be more readable.
If You need a Boolean evaluation, there is definitely no need for ternary operator.
However, there is also = c ? a:b