Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign only if condition is true in ternary operator in JavaScript

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?

like image 945
codiac Avatar asked Feb 21 '13 18:02

codiac


People also ask

How do you assign a value to a ternary operator?

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

Can we use ternary operator in if statement?

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.

How do you use ternary instead of if else?

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 .

Can ternary operator have two conditions?

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.


2 Answers

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); 
like image 95
Bergi Avatar answered Sep 21 '22 12:09

Bergi


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.

like image 20
marekful Avatar answered Sep 20 '22 12:09

marekful