Ternary Operator: When to use it

Putting the mystery to rest

I always had a difficult time knowing whether or not I could use a ternary operator ((condition) ? a : b) in my code. It was never made clear to me about which situation needed to arise in order for this operator to be deployed. Eventually, I figured out this conundrum. It’s time to share this discovery with the world. A ternary operator can be used when something is returned whether a single condition evaluates to true or false. The best way to understand this is through the recursive implementation for computing the factorial of a number.

In the implementation above, you can see that whether the condition evaluates to true or false, the function still returns a value. When you have a single condition being tested that returns a value (if the condition is true), and a default return (if the condition is false), then a ternary operator can be used.

The application of the ternary operator results in a recursive factorial implementation that only requires a single line of code. I know that the time complexity is disgraceful (due to recursion), but the example is second to none. Hopefully this helps someone in their quest to understand this elusive operator.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store