Programming style question: say I'm returning a value that is conditional on a flag, in JavaScript. Is it better to return a conditional value (return bool ? this : that) or conditionally return a value (bool ? return this : return that) and why do you think this?

return b ? x : y;
says "Here's where I return something, and here's what it is: a ternary expression.".

The other option is just a minified `if...else`. Sometimes you need to return inside a conditional, but I'd prefer not to. Having a single place where you return (or as few as possible) is nice.


If there are side-effects of building either of the values, or if there's other stuff happening that depends on the same conditional, then returning from an if/else would make sense.
Also, situations might come up where it's difficult or opaque to build one of the values in-line. If the values don't already exist as variables, and can't be built in-line, then one'll probably use the if/else format.

Sign in to participate in the conversation
Mastodon for Tech Folks

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!