JavaScript: try-finally

[2013-03-11] dev, javascript, jslang
(Ad, please don’t block)
This blog post is a quick reminder of how try-finally works.

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.