I’ve always had to put null in the else conditions that don’t have anything. Is there a way around it?
For example,
condition ? x = true : null;
Basically, is there a way to do the following?
condition ? x = true;
Now it shows up as a syntax error.
FYI, here is some real example code:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
First of all, a ternary expression is not a replacement for an if/else construct – it’s an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
=that is to be assigned the return valuex = truereturns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)In short – the ‘correct’ use of a ternary expression is
Instead of your example
condition ? x=true : null ;, where you use a ternary expression to set the value ofx, you can use this:This is still an expression and might therefore not pass validation, so an even better approach would be
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
UPDATE
In relation to your sample, this is probably more appropriate: