Javascript: `no-nested-ternaries` can cause difficult to understand code

Created on 17 May 2018  路  1Comment  路  Source: airbnb/javascript

The rule states that "Nesting ternary expressions can make code more difficult to understand." However, by enabling the rule engineers often have to create and nae intermediate variables which can also make the code more difficult to understand.

A real world example:

screen_shot_2018-05-16_at_12 31 18_pm_1024

I'd argue that in this case both the variable names and also having to move conditional logic further away from where it is executed make the code more inscrutable.

My recommendation would be disabling the no-nested-ternary rule in the short term and enabling the rule to be a bit more lenient in the long term. Happy to put in a PR if that's the consensus of the maintainers too.

question

Most helpful comment

In general, I'd say that intermediate variables (in the same region of the code) almost always make code easier to understand. I acknowledge that the vagaries of jsx and JS combined which require locating these things in different places may disrupt that, at times.

However, it seems like this might be a better alternative:

{!showPinSaveOverflow && !promotedIsRemovable && saveButton}
{showPinSaveOverflow && !isOwnPin && saveButtonPromotedRemoved}

In general tho, this is complex logic that doesn't really seem to have a clear way to express it - perhaps moving some of this logic into instance methods would help, or, putting this into its own SFC?

Either way I don't think a version with a nested ternary is going to be more readable.

>All comments

In general, I'd say that intermediate variables (in the same region of the code) almost always make code easier to understand. I acknowledge that the vagaries of jsx and JS combined which require locating these things in different places may disrupt that, at times.

However, it seems like this might be a better alternative:

{!showPinSaveOverflow && !promotedIsRemovable && saveButton}
{showPinSaveOverflow && !isOwnPin && saveButtonPromotedRemoved}

In general tho, this is complex logic that doesn't really seem to have a clear way to express it - perhaps moving some of this logic into instance methods would help, or, putting this into its own SFC?

Either way I don't think a version with a nested ternary is going to be more readable.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xgqfrms-GitHub picture xgqfrms-GitHub  路  3Comments

surfaceowl picture surfaceowl  路  3Comments

weihongyu12 picture weihongyu12  路  3Comments

stephenkingsley picture stephenkingsley  路  3Comments

brendanvinson picture brendanvinson  路  4Comments