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???
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???
4 Answers
Reset to default 24Here is the shortest way.
A == 1 && execute_function();
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.
condition ? (runTrue) : (runFalse);
is available in javascript.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
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();
if(condition) doSomething else doSomethingElse
you can writecondition ? doSomething : doSomethingElse
In your case you have just the if condition, while the else is empty, so as @Lloyd wrote ternary is not appropriate in your case – ThanksForAllTheFish Commented Jan 11, 2013 at 9:47