Reputation: 725
I'm trying to express these two ternary operators in one expression. Can someone help me?
var longer = a.length > b.length ? a: b;
var shorter = a.length > b.length ? b : a;
Thanks!
Upvotes: 3
Views: 111
Reputation: 2099
I saw this question was answered already. But, I have attempted it for fun,
shorter = ((a.length < b.length) && (longer = b))||((longer = a)&&false) ? a: b;
UPDATE:
As @MattWhipple suggests, you can make it shorter (you may see warning in the console)
((a.length < b.length) && (shorter = a) && (longer = b)) || ((shorter = b) && (longer = a))
Upvotes: 0
Reputation: 7134
The clearest solution with the 2 values would be something like (may have to adjust the syntax):
[shorter, longer] = [a, b].sort(function(a, b) {return a.length > b.length});
Upvotes: 0
Reputation: 233
You could make the first expression an assignment that gets nested as the condition of the second.... but in this case, I think you should keep the two separate lines in order to avoid obfuscating your code. Nesting the ternaries will not give you a performance boost and therefore serves no useful purpose.
Upvotes: 0
Reputation: 27210
You can do this since JavaScript 1.7 (its 1.8.5 now): Destructuring assignment (Merge into own page/section).
As everyone could (possibly) imagine, the cross-browser compatibility is abysmal. But since this is a homework question I'll leave it here as an answer.
Upvotes: 3
Reputation: 1823
It's not possible if you plan on declaring both variables in the expression.
Upvotes: 2