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?
Yes you can go wild nesting ternaries.
The JavaScript ternary operator also works to do multiple operations in one statement. It's the same as writing multiple operations in an if else statement.
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.
it shows ternary is more faster than if..else statement(Nodejs console, Chrome and Edge) but in the case of Firefox, shows opposite result (Windows 10). The below code gives the 40 average milliseconds for both test. Save this 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
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