Just because you can do something, doesn’t mean you should, and that’s the case with nested ternary operations. Nesting ternary operators
results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you)
scratching their heads and cursing.
Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.
Noncompliant Code Example
function getReadableStatus(job) {
return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded "; // Noncompliant
}
Compliant Solution
function getReadableStatus(job) {
if (job.isRunning()) {
return "Running";
}
return job.hasErrors() ? "Failed" : "Succeeded";
}
Exceptions
This rule does not apply in JSX expressions to support conditional rendering and conditional attributes.
return (
<>
{isLoading ? (
<Loader active />
) : (
<Panel label={isEditing ? 'Open' : 'Not open'}>
<a>{isEditing ? 'Close now' : 'Start now'}</a>
<Checkbox onClick={!saving ? setSaving(saving => !saving) : null} />
</Panel>
)}
</>
);