Assign only if condition is true in ternary operator in JavaScript Assign only if condition is true in ternary operator in JavaScript javascript javascript

Assign only if condition is true in ternary operator in JavaScript


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


An expression with ternary operator must have both values, i.e. for both the true and false cases.

You can however

max = (max < b) ? b : max;

in this case, if condition is false, value of max will not change.


You can just set max to itself if the condition is false.

max = (max < b) ? b : max;

Or you can try using the && operator:

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

Or to keep your code simple, just use an if.

if(max < v) max = b;