Say we have nested ternary statements:
return foo ? 1 : bar ? 2 : 3;
What is the best way to format this code to ensure future readability by others.
Say we have nested ternary statements:
return foo ? 1 : bar ? 2 : 3;
What is the best way to format this code to ensure future readability by others.
This post is the most popular opinion I could find on this. The suggestion there is
return foo ? 1 :
bar ? 2 :
3 ;
To separate function
function getValue(cond1, cond2) {
if(cond1) return 'a';
if(cond2) return 'b';
return 'c';
}
function work() {
const result = getValue(/* some params */);
}
I have a preference for the readability of this style of ternary operator formatting:
return foo
? bar
: baz
? qux
: qiz
? 1
: 2;
I can't tell if this is accepted or not but i use it this way all the time.
Ternary gives you such a natural testing structure that you can make the code very readable just by making it multiline and indenting properly. I strongly believe that the following usage of ternary is the best manifestation of a nested conditional.
return foo ? 1
: bar ? 2
: 3;
In more complicated cases you can make ternary and comma operator work together beautifully. Keep in mind that the last instruction in a comma separated group gets returned automatically. Super handy for ternary.
return foo ? ( doSometingFoo()
, variable++
, collectResult() // and return foo result
)
: bar ? ( doSomethingBar()
, variable--
, collectAnotherResult() // and return bar result
)
: ( doSomethingReject()
, variable = 0
, rejectSomehow() // and return error code
)
For readability just stay away from those statements, they're very easy to misread, if you want something more readable just expand and use normal statments..
Nothing wrong with just having a nested if statement list..
if(foo){
return 1
}else{
if(bar){
return 2;
}else{
return 3;
}
}