Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Perform multiple actions in a ternary condition [duplicate]

Tags:

typescript

Is it possible to execute multiple actions within a ternary condition? Something similar to the following (which does not work):

condition ? () => {
    // Perform multiple actions within this delegate function if the condition is true
} : // Perform an action if the condition is false;
like image 386
Jaime Still Avatar asked Oct 21 '25 04:10

Jaime Still


1 Answers

If you want to do this with a single function, it's simple:

condition ? console.log("true") : console.log("false");

If you want multiple functions to be called, it's a bit more complex:

condition 
    ? (() => {
        console.log("true");
        console.log("still true");
    })()
    : (() => {
        console.log("false");
        console.log("still false")
    })();

This is because when you have a ternary, it will immediately invoke whatever is inside the block. So if you want to call a function, you need to execute that function with ().


Personally, though, I would recommend against this. I think it is much less clear than:

if (condition) {
    console.log("true");
    console.log("still true");
} else {
    console.log("true");
    console.log("still true");
}
like image 150
James Monger Avatar answered Oct 23 '25 21:10

James Monger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!