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?
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?
I think a better approach could be
An expression with ternary operator must have both values, i.e. for both the true and false cases.
You can however
in this case, if condition is false, value of
max
will not change.I think ternary is more suitable try this
You can just set
max
to itself if the condition is false.Or you can try using the
&&
operator:Or to keep your code simple, just use an
if
.Don't use the ternary operator then, it requires a third argument. You would need to reassign
max
tomax
if you don't want it to change (max = (max < b) ? b : max
).An if-statement is much more clear:
And if you need it to be an expression, you can (ab)use the short-circuit-evaluation of AND:
Btw, if you want to avoid repeating variable names (or expressions?), you could use the maximum function:
There isn't a specific operator that isn't the ternary operator, but you can use it like this: