single return of ternary operator

12,430

Solution 1

yes:

(exists == 1) ? execute_function() : false;

runs function if exists is true else wont

Added: Doing just like following would be better:

if( A == 1 ) {
  execute_function();
}

As using ternary operator in above case is not so fruitful, as you are checking only for the true side of the condition and do not care about what's in the false side.

Solution 2

Here is the shortest way.

A == 1 && execute_function();

Solution 3

condition ? (runTrue) : (runFalse);

is available in javascript.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

Solution 4

As someone already mentioned, A == 1 && execute_function(); is the shortest. However, another option is to use a single line if statement:

if( A == 1 ) execute_function();

Share:
12,430
Micah
Author by

Micah

Updated on June 04, 2022

Comments

  • Micah
    Micah almost 2 years

    I wonder if possible to write ternary operator for single return. I tried google online, but couldn't find an answer. or it doesnot called ternary operator??

    Thank you very much for your advice.

    If(A == 1) execute_function(); into A == 1 ? execute_function() //???Possible???

  • Sudhir Bastakoti
    Sudhir Bastakoti over 11 years
    @Till yes, you need to use false side as well, you can use blank string like '', or 0 or false
  • Admin
    Admin over 11 years
    Had exactly the same dilema and figured out (statement) ? true : null; works just as fine
  • Lloyd
    Lloyd over 11 years
    I still argue that in this case ternary just isn't appropriate, you're not gaining anything by using it.
  • Sudhir Bastakoti
    Sudhir Bastakoti over 11 years
    @Lloyd yes you're correct, have updated my answer accordingly