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?
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.
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.
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.
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.
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.
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