Question

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?

Statement is:

my_alert(status ? ('Accepted', 'alert-success') : ('Declined', 'alert-info'))
  • my_alert is a function which has 2 parameters.
  • Status just evaluates to true or false.
  • When I pass more than 1 parameter into the above expression, it doesn't like the use of the comma.

In chrome and firefox when the function runs it displays 'alert-success' or 'alert-info'. It misses out the first parameter.

I've looked on stackoverflow for the answer but by all means it's telling me that what i'm doing is correct.

Any help would be great.

Was it helpful?

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"]);

OTHER TIPS

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);

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"));

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top