I was wondering what if there's any preferable way of returning values conditionally. And if not, if it makes any different for minified Javascript.
I was checking Google Javascript Style guide and they don't name anything about the issue. Same with Airbnb guidelines
Using multiple conditional returns:
function demo(x, y) {
if (x < y) {
return getX();
} else if (x === y) {
return 'equal';
}
return getY();
}
Or having a single return with and making use of a variable:
function demo(x, y) {
var position;
if (x < y) {
position = getX();
} else if (x === y) {
position = 'equal';
} else {
position = getY();
}
return position;
}
The following is a definition of the return statement.
The return statement stops the execution of a function and returns a value from that function.
Clearly, a conditional return would have to include a condition before that return
.
About preference, as the word implies, it is really is a matter of habits.
If you're used to one syntax from, say, another language, or you just like it better - use it, as it will probably reduce syntax errors.
About minifying the code, I believe the switch/case syntax best works for simple conditions, and the ternary operation fits well for two-side conditions.
(Caution! philosophical paragraph ahead)
But again, in the end, the important thing, I believe, is that you will understand the code you write. And, with experience, you will find what suits you best.