Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 723
lologic Avatar asked Nov 05 '17 20:11

lologic


2 Answers

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.

like image 111
tadman Avatar answered Sep 20 '22 00:09

tadman


It's very much possible! You could use this:

a ? b : b ? c : d
like image 36
Josh Chinedu Avatar answered Sep 21 '22 00:09

Josh Chinedu