javascriptshorthand-if

JS shorthand If doing more than one operations


a==b? do 'x' : do 'y' ;

works fine

how would you write to do two things for example?

> a==b? do 'x' and do 'z' : do y ;

Solution

  • A comma sounds like what you're looking for.

    (a == b) ? (x, z) : y
    

    x and z can be variables, in which case their values will just be returned by that expression, or they can be actual operations, and in this case too they'll be evaluated, i.e. executed.

    So, if you do:

    (true == true) ? (alert('Hey'), alert('there')) : alert('Aw...')
    

    It'll show 2 alerts, the first showing "Hey", and the second - "there".

    Also, it doesn't sound like this is very important to you, but it should be noted that the second expression's value (whatever is returned by executing y) will be returned as the result of the complete expression.