0 day streak
javascript / intermediate
Snippet

The Power of 'finally' in Control Flow

The finally block always executes regardless of whether an error was thrown or a return statement was encountered in try/catch. Importantly, a return in finally will override any previous return values.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function checkFlow() {
try {
console.log('Step 1');
return 'Result from Try';
} catch (err) {
return 'Result from Catch';
} finally {
console.log('Step 2: Cleanup');
// Returning here overrides the previous return value!
return 'Final Override';
}
}
console.log(checkFlow());
// Output:
// Step 1
// Step 2: Cleanup
// Final Override
Breakdown
1
finally { ... }
A block that executes after try and catch, used for mandatory cleanup logic.
2
return 'Final Override';
This line hijacks the function's output, demonstrating that finally has the last word.