Option to ignore no-nested-ternary for daisy-chained ternaries only
See original GitHub issueWhat rule do you want to change?
no-nested-ternary
Does this change cause the rule to produce more or fewer warnings? Fewer warnings.
How will the change be implemented? (New option, new default behavior, etc.)?
New option, e.g.: allowDaisyChain: true
Please provide some example code that this change will affect:
var foo = false;
var bar = true;
var baz =
foo ? 'foo' :
bar ? 'bar' :
null;
var qux =
!foo ?
!bar ? null : 'bar'
: 'foo';
(ESLint Demo)
Both baz
and qux
will be 'bar'
, but the code for the assignment to baz
is far more easy to reason about because it’s daisy-chained and not just nested.
It’d be great to allow nested ternaries of that type whilst still disallowing the more convoluted qux
form.
What does the rule currently do for this code? Raises 2 errors:
5:2 - Do not nest ternary expressions. (no-nested-ternary) 10:2 - Do not nest ternary expressions. (no-nested-ternary)
What will the rule do after it’s changed? Raise only one error:
10:2 - Do not nest ternary expressions. (no-nested-ternary)
For a more in-depth analysis of nested ternaries and how the daisy-chained version is useful because it’s like a switch statement turned into an expression, capable of more than just strict equality checks of one value, see here: https://medium.com/javascript-scene/nested-ternaries-are-great-361bddd0f340#c69a
Issue Analytics
- State:
- Created 5 years ago
- Comments:10 (4 by maintainers)
Top GitHub Comments
I would love this option.
I have missed to be able to do this for a long time (with still good linting active + integration with prettier formatting, etc - i.e. an exception option to the no-nested-ternary rule).
I’m thinking about this article on the subject that argues for the use of chained ternaries, and that I agree on: https://medium.com/javascript-scene/nested-ternaries-are-great-361bddd0f340
Also as @zeorin said:
Yes.
The more I think about it, the more I like
allowAlternate
. Although it’s likely to be unfamiliar to most devs at first, it is the closest thing we have to a formal term for it (that I’m aware).With an explanation of the terms “consequent” and “alternate” in the docs for this option I think it’ll be clear, and we’ll also be expanding the available technical vocabulary for devs that (like me) are unfamiliar with these terms.