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.
3
Answers
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:
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.
Update: your comment says that you have multiple functions like
falseOrNumber
. If so, you can do this:You mentioned that your use case is to call this many times over and over in the same
otherFunction
.If you are trying to test several numbers in sequence, you can do it like so:
If you need to do this in a loop, you can share one variable:
If your usecase is as what @maraaaaaaaa said, in the future you might be able to do something like this if this proposal gets accepted:
testcases.values()
returns an iterator which goes over all elements, one by one..map()
map those with a function (in this case,falseOrNumber
) on the fly, yet returns another iterator and.find(Boolean)
returns the first mapped element which is not falsy.Unlike
testcases.map()
,testcases.values().map()
is lazy: it only evaluate as needed. This is also the case when it comes to bothArray#find()
andIterator#find()
(there’s no docs for this just yet, only this).Try it (this doesn’t work yet):