Sunday, May 19, 2024
124
rated 0 times [  126] [ 2]  / answers: 1 / hits: 121799  / 11 Years ago, thu, february 21, 2013, 12:00:00

Is it possible to do something like this in JavaScript?



max = (max < b) ? b;


In other words, assign value only if the condition is true. If the condition is false, do nothing (no assignment). Is this possible?


More From » ternary-operator

 Answers
14

Don't use the ternary operator then, it requires a third argument. You would need to reassign max to max if you don't want it to change (max = (max < b) ? b : max).



An if-statement is much more clear:



if (max < b) max = b;


And if you need it to be an expression, you can (ab)use the short-circuit-evaluation of AND:



(max < b) && (max = b)


Btw, if you want to avoid repeating variable names (or expressions?), you could use the maximum function:



max = Math.max(max, b);

[#80074] Wednesday, February 20, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;