Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operators. Possible for a one sided action?

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?

like image 808
bashleigh Avatar asked Jan 25 '13 11:01

bashleigh


People also ask

Can ternary operators have more than 1 condition?

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.

What are the three conditions in a 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.

Can we use ternary operator without else condition?

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.

Why ternary operator should not be used?

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.


2 Answers

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();
like image 127
KingCrunch Avatar answered Sep 23 '22 19:09

KingCrunch


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():;

like image 37
Ivaylo Strandjev Avatar answered Sep 22 '22 19:09

Ivaylo Strandjev