I have the following code
function x () {
return a ? (b ? 'result2' : 'result1') : 'result1';
}
Is there a better way to combine these two conditions into one?
I have the following code
function x () {
return a ? (b ? 'result2' : 'result1') : 'result1';
}
Is there a better way to combine these two conditions into one?
Well, it depends on how better is defined. There are several questions to address for an answer that would fit the desired solution.
Is a version without boolean operations better?
function x() {
var toReturn = "result1";
if ( a ) {
if ( b ) {
toReturn = "result2";
}
}
return toReturn;
}
Is a version without a ternary operation and with an or logical operation better?
function x() {
if ( !a || !b ) { return "result1"; }
return "result2";
}
Is a version with a logical and and a ternary operation better?
function x() {
return ( a && b ) ? "result2" : "result1";
}
Just to ilustrate how complex the question is. Since better is a vague term better look into it before choosing an alternative.
You can reduce this to a single expression with one ternary operator by using the logical AND operator (&&):
function x () {
return a && b ? 'result2' : 'result1';
}
This provides the same output:
| a | b | return value |
|---|---|---|
true |
true |
result2 |
false |
false |
result1 |
false |
true |
result1 |
true |
false |
result1 |