VeryOddlySpecific
VeryOddlySpecific

Reputation: 335

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?

Upvotes: 27

Views: 23194

Answers (4)

Alex Wayne
Alex Wayne

Reputation: 187034

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.

Upvotes: 40

Michiel J Otto
Michiel J Otto

Reputation: 2311

Sure, you can just wrap your statements in parentheses*()* and separate them with a comma*,*

condition ? (doThis, andThis) : (doThat, andThat)

In your case (OP):

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

Upvotes: 1

dtmuturi
dtmuturi

Reputation: 91

For some reason what worked for me was returning both functions as objects in an array. Otherwise the ternary operator only returned the last function. See below example:

isTrue ? [fucnctionOne(), functionTwo()] : functionThree()

Upvotes: 5

Paul Kaplan
Paul Kaplan

Reputation: 2885

You can always wrap anything into an anonymous function and call it immediately, the so called Immediately Invoked Function Expression (IIFE), like so

isTrue ? (function() { functionOne(); functionTwo() })() : functionThree();

But as you can see it looks pretty darn terrible and is a pretty bad misuse of the ternary operator (it doesn't return anything useful) so I'd really recommend against doing that.

Upvotes: 6

Related Questions