Skip to content Skip to sidebar Skip to footer

Proper Use Of A Comma In Javascript Ternary Operator

Rather than use an if else statement, I'm trying to use the ternary operator but have a syntax error somewhere in my statement. Can someone tell me where I am going wrong? Stateme

Solution 1:

Well, the comma operator does the following:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

That means, ('Accepted', 'alert-success') evaluates to 'alert-success' (as you already noticed). The comma here is different than the comma that separates function arguments. You cannot use it to pass two arguments to a function.

What you can do is store both arguments in an array and use .apply to pass them to the function:

// this is not the comma operator either, this is array literal syntax.var args = status ? ['Accepted', 'alert-success'] : ['Declined', 'alert-info'];
my_alert.apply(null, args);

Solution 2:

I don't think ternary operators can be used to control two values like that:

How about separating them:

my_alert(($status?"Accepted":"Declined"),($status?"alert-success":"alert-info"));

Solution 3:

Alternatively, you could just wrap the function call in the ternary statement...

status ? my_alert("Accepted", "alert-success") : my_alert("Declined", "alert-info");

UPDATE:

Robin van Baalen makes a good suggestion...

my_alert.apply(this, status ? ["Accepted", "alert-success"] : ["Declined", "alert-info"]);

Solution 4:

You can't use the comma like that. If you want to pass 2 parameters, you need to use 2 ternary statements.

my_alert((status ? 'Accepted' : 'Declined'), (status ? 'alert-success' : 'alert-info'));

In your case, the comma is read a the comma operator, which evaluates both operands and returns the last one. So, your ternary statement was equivalent to:

my_alert(status ? 'alert-success' : 'alert-info')

Post a Comment for "Proper Use Of A Comma In Javascript Ternary Operator"