I have a function that returns either false or a number other than 0. Now I’m calling this function in another function to conditionally return the number.
function falseOrNumber() { ... }
function otherFunction() {
// ...
if (falseOrNumber()) return falseOrNumber()
// ...
}
Now I was wondering, if there is an elegant way to perform this in one line without calling falseOrNumber() twice.
So I’m not looking for the obvious solution:
let i = falseOrNumber()
if (i) return i
This is nothing game changing, but I’ve encountered similar situations several times in the past and I’d like to know if there is a cleaner way.
>Solution :
If you assign the return value of the function to a variable inside the if statement, you can re-use it with the return statement:
function falseOrNumber() { ... }
function otherFunction() {
// ...
let result;
if(result = falseOrNumber()) return result;
// ...
}
If you want more elegance, there is probably a way to have one return statement for the entire function, instead of returning early. You can also use a comma expression to turn multiple expressions into a one-liner.
function otherFunction() {
return falseOrNumber() || (other, code, here);
}
Update: your comment says that you have multiple functions like falseOrNumber. If so, you can do this:
function otherFunction() {
return falseOrNumber() || somethingElse() || orSomethingElse();
}