Does finally run if try has a return?
This is one of the most common "gotchas" in JavaScript!
The answer is yes, the finally block always runs, even if try has a return inside it.
The general rule
Regardless of whether there was an error, there was a return, or there was a throw, the
finallyblock is guaranteed to run before the function exits.
Example 1. return inside try
javascript
function test() {
try {
console.log("Inside try");
return "Value from try";
} finally {
console.log("The finally block runs anyway");
}
}
console.log("Result:", test());Output:
javascript
Inside try
The finally block runs anyway
Result: Value from tryYou can see that:
- First, the code inside
tryruns. - Then, before the value is returned,
finallyis called. - Only after that does the function return its result.
Example 2. return and throw inside try
javascript
function example() {
try {
console.log("Before returning");
return "Return from try";
} catch {
console.log("catch will not run");
} finally {
console.log("finally runs anyway");
}
}
console.log(example());Output:
javascript
Before returning
finally runs anyway
Return from tryExample 3. return and an error: finally still fires
javascript
function example() {
try {
throw new Error("Error in try");
} catch (e) {
console.log("Caught:", e.message);
return "Return from catch";
} finally {
console.log("finally runs anyway");
}
}
console.log(example());Output:
javascript
Caught: Error in try
finally runs anyway
Return from catchExample 4. finally can override the return
If finally also has a return,
it replaces the result that was returned from try or catch.
javascript
function example() {
try {
return "From try";
} finally {
return "From finally";
}
}
console.log(example());Output:
javascript
From finallyThat's why adding a return inside finally is a bad practice:
it makes the function's behavior unpredictable.
Example 5. finally runs even on an error
javascript
function example() {
try {
throw new Error("Error!");
} finally {
console.log("finally fires even on an error");
}
}
example(); // Uncaught Error: Error!Output:
javascript
finally fires even on an error
Uncaught Error: Error!Summary
| Scenario | Does finally run? | What happens |
|---|---|---|
| No errors | Yes | After try |
| There is an error | Yes | After catch |
There is a return in try | Yes | Before the function exits |
There is a return in catch | Yes | Before the function exits |
There is a throw | Yes | Before the exception is thrown |
There is a return in finally | Yes, and it overrides the result |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.