-2
\$\begingroup\$

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?

\$\endgroup\$
3
  • \$\begingroup\$ BTW, I'm pretty sure this was closed because it's too generic and short to be from a project. \$\endgroup\$ Commented Jan 15, 2022 at 19:43
  • \$\begingroup\$ Actually I made a mistake in my question, I swapped the return result.. \$\endgroup\$ Commented Jan 17, 2022 at 7:41
  • \$\begingroup\$ The reason why I rolled this back is that code in the question should not change after an answer is given. Normally I'd suggest asking a new question, but such a question would likely be closed for the same reason as this one. It's possible that this question might fit on another site in the stack exchange network. Or you could ask a new question with sufficient context here. \$\endgroup\$ Commented Jan 19, 2022 at 18:25

2 Answers 2

4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Actually I made a mistake in my question, I swapped the return result.. is there a way to write the new statement with ternary? \$\endgroup\$ Commented Jan 17, 2022 at 7:42
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Actually I made a mistake in my question, I swapped the return result.. is there a way to write the new statement with ternary? \$\endgroup\$ Commented Jan 17, 2022 at 7:42

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.