Hacker News new | ask | show | jobs
by mostlylurks 1060 days ago
I see this opinion voiced all the time, and I can never understand how people can struggle with something like nested ternaries. Surely a straightforward use (i.e. not a weird edge case) of very basic syntax shared by most widely used programming languages shouldn't cause much of an issue?

It should also be easier to reason about nested ternaries than an equivalent set of nested if-elses, because at least with ternaries you know that every branch is an expression resulting in some value (and statically typed languages ensure that these values have the correct type), whereas if-else blocks can contain anything, are likely (and in most languages (which lack if-else expressions), forced) to mutate things, and have no guarantee of producing the result that you were expecting, unlike ternaries (especially in statically typed languages).

1 comments

Should ternaries be left or right associative?
Right associative! It's just one of the many rites of passage for people working with PHP to get bitten by its left associative ternaries. Naked nested ternaries are deprecated now, but maybe one day, PHP can have right associative ternaries.
Except when it's not, like in perl.
Not sure what you mean, but ternaries are right-associative in Perl just like most other languages. PHP is the odd one out.
Except when they're not.
And when is that? The docs just say it's right associative[1]. And while it's been a long time since I've written any nontrivial Perl, I don't remember ever having ?: be left associative.

[1] https://perldoc.perl.org/perlop