JavaScript Interview Questions

Try/Catch/Finally

I had an interview a while back and one of the questions was to do with try/finally.

Given this function:

function test () {
  try {
    return("hello")
  } finally {
    console.log("finally");
  }
}

What gets output from the below?

console.log(test());

The answer is actually:

> finally
> hello

How come?

Because the try catch is in a function, the finally gets executed after the try, then the result of the try is returned. More information on try-catch-finally is on bennadel.com - I finally understand the finally part of a try catch.