AnApprentice
AnApprentice

Reputation: 110950

Unconditional use of conditional expression for default assignment

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

Answers (3)

T.J. Crowder
T.J. Crowder

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

DuFuS
DuFuS

Reputation: 371

Little bit safer is to use : nullish operator ?? instead of a logical operator ||

Upvotes: 0

Oro
Oro

Reputation: 1867

It is not inherently wrong, but it is better written as:

myOverride || MAGIC_HOST

as explained here.

Upvotes: 3

Related Questions