Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of execution with a javascript finally block, following a return in a try block

Tags:

javascript

In relation to: Java try-finally return design question

This doesn't quite answer my question also may not be relevant since it's java and not javascript: What is the order of execution in try,catch and finally

I understand that putting a return in a finally block will take precedence over a return in a catch block, however how does the sequence events work with the following code?

function confusion(){
  var test = "a";
  try{
    return test;
  }
  finally{
    test = "b";
  }
}

console.log("Result", confusion()); //"a"

My general understanding of returning of anything is that control usually returns to the context of where the method is being called, so the fact that execution continues is kind've confusing to me.

In this scenario I thought it might play out something like:

-Function set to return test -> finally changes value of test -> test is returned with updated value.

But instead it seems like some sort've state is held for the try block and finally misses the timing?

like image 734
camjocotem Avatar asked Apr 23 '17 13:04

camjocotem


1 Answers

When you return out of a try or catch block with an associated finally block, execution enters the finally block because that's the purpose of it: To handle common completion actions for the try/catch.

In your code, what happens as of the return is:

  1. The value of test is read from the variable and set aside for use later.

  2. Control passes to finally.

  3. Code in finally changes the value of the variable test (which has no effect on the value that was set aside in #1).

  4. When the end of the finally block is encountered, the function returns, using the value set aside in #1 as its return value.

This is covered in The try Statement / Runtime Semantics: Evaluation in the specification, and perhaps more readably in try...catch on MDN under "The finally clause."

Note that the finally can interrupt the return process, by either throwing an exception, or returning a new value. If it does either of those things, it wins over the return in the try (or catch).


Side Note re your linked Java question: JavaScript's try/catch/finally works just like Java's except: 1. You can only have one catch block because exceptions aren't typed, and 2. JavaScript doesn't have Java's try-with-resources statement.

like image 53
T.J. Crowder Avatar answered Oct 14 '22 02:10

T.J. Crowder