Question: what is the output the following code?
var count = 0;
function foo() {
try {
return count;
} finally {
count++;
}
}
console.log(foo());
console.log(count);
The output is:
0
1
Thus:
- The finally clause is always executed, no matter what happens inside the try clause (return, exception, break, normal exit).
- However, it is executed after the return statement.
3 comments:
What should happend with :
count = foo();
Does this look right?
1) return count;
2) count ++ //count become 1
3) count = 'what was returned, i.e. 0'
That looks OK, you’d have to step through it in a debugger.
In that case the function would return undefined since count is only assigned after the return, so it's still undefined when the return statement executes. Next, the finally block will add 1 to undefined which evaluates to NaN.
Post a Comment