Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JavaScript ternary operator support 3 conditions?

Given the following JavaScript ternary operator, is it possible to enable this to support 3 conditions versus the current two?

const color = d.y >= 70 ? "green" : "red";

I would essentially like the following logic:

>= 70, color = green;
between 69-50, color = yellow;
< 50, color = red;

Is this possible with a 1 line ternary or do I need a IF statement?

like image 522
AnApprentice Avatar asked Oct 02 '17 17:10

AnApprentice


People also ask

Can we use multiple conditions in ternary operator JS?

Yes, you can use multiple condition in Ternary Operator.

What are the 3 conditional operators?

There are three conditional operators: && the logical AND operator. || the logical OR operator. ?: the ternary operator.

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 many expressions are allowed inside ternary operator?

Summary. A Ternary Operator in Javascript is a special operator which accepts three operands.


2 Answers

you can do

const color = d.y >= 70 ? "green" : (d.y < 50 ? "red" : "yellow");
like image 164
marvel308 Avatar answered Oct 15 '22 04:10

marvel308


you can stack it like this:

condition1 
  ? result1 
  : condition2 ? result3 : result4
like image 20
Z.D. Avatar answered Oct 15 '22 04:10

Z.D.