Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript assiging multiple values to `ternary` operator

Tags:

javascript

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.

like image 535
user2024080 Avatar asked May 12 '17 05:05

user2024080


People also ask

Can you do multiple things in a ternary operator?

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.

How can a ternary operator return multiple values?

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.

Can we use multiple conditions in ternary operator JS?

Yes, you can use multiple condition in Ternary Operator.

Can ternary operator have 3 conditions?

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.


2 Answers

var size=3;
var val1=null;
var val2=null;
size === 3 ? (  val1=999,val2=100 )  : 0;
console.log(val1,val2)
like image 184
Erdogan Oksuz Avatar answered Oct 22 '22 15:10

Erdogan Oksuz


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)
like image 34
prasanth Avatar answered Oct 22 '22 15:10

prasanth