I've run into some problems in my code, and so I have narrowed it down to this simple use-case:
function func() {
try {
return true;
}
finally {
return false;
}
}
console.log(func());
To my extreme surprise, the printout of the code above is false
.
Now, I could easily solve it with:
function func() {
try {
return true;
}
catch (error) {
}
return false;
}
In fact, that was my original code, but then I figured it would look nicer with finally
.
I have read this MDN post, which gives three forms for the try
statement:
try
...catch
try
...finally
try
...catch
...finally
The 2nd form looks perfect for my use-case.
I am finding it extremely bewildering that the return statement in the finally
part "overrides" the return statement in the try
part.
In fact, I am not even sure how this behavior is achieved via "compilation" (double quoting, because I know that this term doesn't really apply for Javascript).
Common sense tells me that the code inside the finally
part is placed at the end of the try
part and (optionally) at the end of the catch
part.
In fact, I'm pretty sure that this is the case in compiled languages like C++ and Java, though for the sake of my question, it is not really important whether or not this is how finally
is implemented behind the scene.
My question - how is it possible for the return statement of the try
part to be so brutally ignored here? What have I missed about finally
?