Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I execute multiple functions on the result of a ternary operation?

I have an if/else statement that results in two functions being called if it evaluates as true.

if (isTrue) {
    functionOne();
    functionTwo();
} 
else {
    functionThree();
}

I would like to be able to put that in a ternary statement like this:

isTrue ? (functionOne(), functionTwo()) : functionThree();

Is this possible?

like image 817
VeryOddlySpecific Avatar asked Mar 09 '15 19:03

VeryOddlySpecific


People also ask

How do you perform multiple operations in a ternary operator?

You can use the comma operator to execute multiple expressions in place of a single expression: arr[i] % 2 === 0? (evenCount++, totalCount++) : (oddCount++, totalCount++); The result of the comma operator is the result of the last expression.

Can we execute multiple statements in ternary operator?

Yes, we can, but with one proviso… There is no block demarcation so that action should be simple, else it would be better to abstract it away in a function and call the function from the ternary.

How do you write 3 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.

What operator allows to wrap multiple functions together?

Combining FOs. Besides just operating on single functions, function operators can take multiple functions as input. One simple example of this is plyr::each() . It takes a list of vectorised functions and combines them into a single function.


1 Answers

Your example is indeed valid javascript. You can use a comma to separate expressions, and wrap that in a single statement with parentheses for the ternary.

var functionOne   = function() { console.log(1); }
var functionTwo   = function() { console.log(2); }
var functionThree = function() { console.log(3); }
var isTrue = true;

isTrue ? (functionOne(), functionTwo()) : functionThree();
// 1
// 2

isTrue = false;
isTrue ? (functionOne(), functionTwo()) : functionThree();
// 3

However, this is not advisable. Your version with an if statement is far more clear and readable, and will execute just as fast. In most codebases I've ever seen or worked with, the comma operator is never used this way as it's far more confusing than it is helpful.

Just because you can, doesn't mean you should.

like image 168
Alex Wayne Avatar answered Oct 28 '22 18:10

Alex Wayne