2

I've been looking on stack overflow and searching blog posts for info on this and can't seem to find a definitive answer.

It regards using if condition or a ternary to execute functions. Is there a "best practice" regarding which we should use?

Let's say we have 2 functions and that one of them will execute based on some boolean value.

We can write functionality like this using traditional if/else statements:

if (boolean) {
  doThis()
} else {
  doThat()
}

Alternatively, we can write something functionally equivalent like this:

boolean ? doThis() : doThat()

Generally, most ternaries I use and see from others are used for assignment, and not to execute functions.

Everything on stack overflow and blogposts that I've seen just state that, "Yes, that's a thing. We can execute functions in ternaries".

Nothing ever speaks to whether we should favor one over the other. Is there a best practice when it comes to which one you should choose?

It seems like it'd be completely fine to use one if the functionality you'd like to execute conditionally is just one function. If you have more then that it seems like if conditions should be favored for readability.

So, with all that context, here's the question:

Does it just depend on the situation? Or should we always favor if conditions for function calls and relegate ternaries strictly to assignment?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Andrew Kim
  • 3,145
  • 4
  • 22
  • 42
  • 2
    possible duplicate of https://stackoverflow.com/questions/4192225/prettiness-of-ternary-operator-vs-if-statement – Naga Sai A Jul 25 '19 at 16:51
  • there is no better, you're asking for an opinion. I say either's fine if short and readable. – dandavis Jul 25 '19 at 16:54
  • It depends on how **you** feel about ternaries. Do you find them more readable? In programming "readable" can have an objective measure - do you spot bugs in the logic easier in code with if/else than ternary operator? If yes if/else is 100% more preferable so you'd only use ternary in places where it makes sense (eg, React templates or string templates that expects expressions). Not everyone fell the same depending on your code style, experience etc. – slebetman Jul 25 '19 at 16:58
  • yeah, that makes total sense, I was just wondering what community writ large feels, if there was a community preference at all, as it were – Andrew Kim Jul 25 '19 at 17:00
  • Use `?:` if you're interested in the return value. – melpomene Jul 25 '19 at 17:04

0 Answers0