How to I execute multiple functions on the result of a ternary operation?
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.
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()
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.