Don't worry, the function above definitely returns 'one', but in this case the first return statement prevents the others from executing.

In JS functions, the last return wins

submited by
Style Pass
2021-06-24 08:30:04

Don't worry, the function above definitely returns 'one', but in this case the first return statement prevents the others from executing. The last return is return 'one', and that's the one that wins. Sure, it's also the first return, but I'm still right. [folds arms and looks smug]

The above logs 'one', 'two', 'three', 'four'. The finally block always runs after a try/catch, even if the try or catch return.

I hadn't used finally much in JavaScript, but I find myself using it quite a bit in async functions, in patterns like this:

…and the result of calling manyHappyReturns() is 'three'. The last return always wins. The same happens in Java and Python too. Thanks to Daniel Ehrenberg for making me aware of this little quirk!

Here, promise fulfils with 'one'. This is probably because promise reactions are callbacks, and the caller of a callback (which is the promise in this case) has no way of telling the difference between a function that runs return undefined and one that doesn't run return at all. Since it can't mimic the finally edge case above, it just ignores it.

Leave a Comment