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?
The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?
Yes you can. A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2. If condition2 is correct, then the output is Expression1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With