Reputation: 110950
I'm getting the following linting error: Unconditional use of conditional expression for default assignment
What is wrong with the below?
(myOverride) ? myOverride : MAGIC_HOST,
Where if myOverride is defined I want to use myOverride, if it is not defined I want to use the env var MAGIC_HOST
.
Upvotes: 2
Views: 5588
Reputation: 1074168
Apparently you're using ESLint (as that error is an ESLint) error. It's because of the no-unneeded-ternary
rule which is meant to flag up unnecessary use of the conditional operator (they call it the "ternary")¹. From the linked docs:
Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical OR can be used to provide the same functionality. Here is an example:
// Bad var foo = bar ? bar : 1; // Good var foo = bar || 1;
So the rule is telling you to use myOverride || MAGIC_HOST
instead.²
You don't have to, the code you've shown isn't wrong. It's just it doesn't pass that ESLint rule.
¹ "they call it the 'ternary'" - The conditional operator is a ternary operator (an operator accepting three operands, just like *
is a binary operator — an operator accepting two operands). And it is, for now, the only ternary operator JavaScript has. But that doesn't necessarily always have to be true as the language evolves. It's correctly called the conditional operator.
² Depending on what the valid values for myOverride
are, you may or may not want myOverride ?? MAGIC_HOST
these days. The difference is that with ??
, only the values null
and undefined
are replaced with MAGIC_HOST
, but with ||
any falsy value is replaced with MAGIC_HOST
. For a string, you may want to stick with ||
, but it's good to know your options.
Upvotes: 10
Reputation: 371
Little bit safer is to use : nullish operator ??
instead of a logical operator ||
Upvotes: 0