How to assign multiple values to ternary
operator? is that not possible? I tried like this, but getting error:
size === 3 ? ( var val1=999, var val2=100; ) : 0;
and
size === 3 ? ( var val1=999; var val2=100; ) : 0;
above both approach throws error. how to set both var val1
and var val2
;
I can directly declare it. But I would like to know the ternary operator approach here.
The JavaScript ternary operator also works to do multiple operations in one statement. It's the same as writing multiple operations in an if else statement.
You need to wrap the assignments in parenthesis and use the comma operator which separates the assignments, instead of semicolon, which separates statements. The semicolon ends the conditional (ternary) operator ?: before reaching the : , which is a needed part of the syntax and this leads to an error.
Yes, you can use multiple condition in Ternary Operator.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
var size=3;
var val1=null;
var val2=null;
size === 3 ? ( val1=999,val2=100 ) : 0;
console.log(val1,val2)
Its a syntax error .You could use like this separate call
var size=3;
var val1 = size === 3 ? 999 : 0;
var val2 = size === 3 ? 100 : 0;
console.log(val1,val2)
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