15

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

3 Answers3

50

you can do

const color = d.y >= 70 ? "green" : (d.y < 50 ? "red" : "yellow");
marvel308
  • 10,288
  • 1
  • 21
  • 32
11

you can stack it like this:

condition1 
  ? result1 
  : condition2 ? result3 : result4
Z .
  • 12,657
  • 1
  • 31
  • 56
6

Just have a second ternary operator:

const color = d.y >= 70 ? "green" : d.y >= 50 ? "yellow" : "red";
PeterMader
  • 6,987
  • 1
  • 21
  • 31