Javascript – Ternary Operator in JavaScript With Multiple Expressions

conditionaljavascriptjqueryternary-operator

the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();

Obviously, this isn't valid. Notice the ";" between the appendTo() and the_styles=null. How do I write it on 1 line and still have multiple expressions like that?

Best Answer

Use the comma operator this way:

the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles =  $('.stylesheet').detach();

Here's what the Mozilla Developer Center writes about the comma operator:

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator