First of all, the triple expression does not replace the if / else construct - its equivalent to the if / else construct that returns a value. That is, the if / else clause is code, a three-dimensional expression is an expression , which means that it returns a value.
This means a few things:
- use ternary expressions only when you have a variable on the left
= to which the return value should be assigned - use only ternary expressions when the return value must be one of two values ββ(or use nested expressions if appropriate)
- each part of the expression (after? and after :) should return a value without side effects (the expression
x = true returns true, since all expressions return the last value, but also change x without x, which have any effect on the returned value)
In short, the "proper" use of ternary expression
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ; condition ? x=true : null ; where you use a ternary expression to set the value of x , you can use this:
condition && (x = true);
This is still an expression and therefore cannot pass the test, so even a better approach would be
void(condition && x = true);
The latter will pass the test.
But then again, if the expected value is logical, just use the result of the condition expression itself
var x = (condition);
UPDATE With respect to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
Sean Kinsey May 29 '10 at 2:08 a.m. 2010-05-29 02:08
source share