DEV Community

Julien Gonzalez
Julien Gonzalez

Posted on

Nested Ternaries Considered Useful

Consider this function that returns a discount rate for a given age:

const get_discount = age => {
  if (age <  5) return 1;
  if (age < 12) return 0.5;
  if (age < 25) return 0.3;
  if (age < 65) return 0;
                return 0.4;
};
Enter fullscreen mode Exit fullscreen mode

Using nested ternaries we can remove the fluff and focus on the intent:

const get_discount = age =>
    age <  5 ? 1
  : age < 12 ? 0.5
  : age < 25 ? 0.3
  : age < 65 ? 0
             : 0.4;
Enter fullscreen mode Exit fullscreen mode

Unfortunately nested ternaries tend to be frowned upon. When not outrightly banned, formatting rules often cause them to be laid out in a rather unattractive fashion:

const get_discount = age =>
  age < 5
    ? 1
    : age < 12
      ? 0.5
      : age < 25
        ? 0.3
        : age < 65
          ? 0
          : 0.4;
Enter fullscreen mode Exit fullscreen mode

But using nested ternaries over a sequence of if isn't an either-or choice.

Say we wanted to compute the discount rate on the fly. You can't just swap the nested ternaries without creating an intermediate variable first:

const apply_discount = (price, age) =>
  price - (price * ( age <  5 ? 1
                   : age < 12 ? 0.5
                   : age < 25 ? 0.3
                   : age < 65 ? 0
                              : 0.4));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)