I've used ternary operators for a while and was wondering if there was a method to let say call a function without the else
clause. Example:
if (isset($foo)) {
callFunction();
} else {
}
Now obviously we can leave out the else
to make:
if (isset($foo)) {
callFunction();
}
Now for a ternary How can you 'by pass' the else clause if the condition returns false?
isset($foo) ? callFunction() : 'do nothing!!';
Either a mystery or not possible?
Such issues can be tackled using multiple ternary operators in a single statement. In the above syntax, we have tested 2 conditions in a single statement using the ternary operator.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
A ternary operation is called ternary because it takes 3 arguments, if it takes 2 it is a binary operation. It's an expression returning a value. If you omit the else you would have an undefined situation where the expression would not return a value. You can use an if statement.
They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.
Short-circuit
isset($foo) and callFunction();
Reverse the condition and omit the second argument
!isset($foo) ?: callFunction();
or return just "something"
isset($foo) ? callFunction() : null;
However, the ternary operators is designed to conditionally fetch a value out of two possible values. You are calling a function, thus it seems you are really looking for if
and misuse ?:
to save characters?
if (isset($foo)) callFunction();
Why would you use a ternary operator in this case? The ternary operator is meant to be used when there are two possible scenarios and doesn't make much sense in the case where you only care about the if
case. If you have to do it however, simply leave the case empty: (cond)?do_something():;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With