Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator in JavaScript With Multiple Expressions?

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?

like image 707
Oscar Godson Avatar asked Jul 02 '10 18:07

Oscar Godson


People also ask

Can we use multiple conditions in ternary operator JS?

Yes you can go wild nesting ternaries.

Can you do multiple things in a ternary operator?

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.

Can ternary operator have 3 conditions?

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.

Which is better ternary operator or if-else in JavaScript?

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.


1 Answers

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

like image 179
Andrea Zilio Avatar answered Nov 15 '22 19:11

Andrea Zilio