javascriptecmascript-6

can I use `else if` with a ternary operator?


Can I only use if and else in a statement in ternary operator syntax or can I also somehow include an else if?

example:

if(a) {
   x
}
else if(y) {
   c
}
else {
   b
}

Solution

  • Unlike an if with optional else or optional else if branches, a ternary operator has two and only two branches.

    It's actually a part of the name. Where + in a + b is a binary operator, that is it has two operands, ? has three, as in a ? b : c, and is termed ternary because of that. Technically there could be other ternary operators beyond ? but in most languages they don't exist, so it is generally understood that the name "ternary" means the ? operator.

    You can have else if like functionality if you sub-branch the second clause:

    a ? b : (c ? d : e)
    

    This is usually a bad idea as ternary operations can be messy to start with and layering like this is usually an express train to unmaintainable code.

    It is much better to write:

    if (a) {
      b
    }
    else if (c) {
    {
      d
    }
    else {
      e
    }
    

    This is more verbose, but abundantly clear.

    If you use ternaries too agressively you'll end up with code like:

    a()?c?d?e:f:g:h?i(j?k:l?m:n):o
    

    Where it's anyone's guess what's going on in there.