JavaScript finally: Cleanup and Completion Order
Quick answer
Finally executes when control leaves a try or catch, whether normally, by return or by throw. It is appropriate for cleanup that should accompany those paths.
How it works
try { ... } finally { ... } is valid without catch. A normally completed finally preserves a pending return or throw. If finally itself returns or throws, that abrupt completion replaces the earlier one. Cleanup can fail; design cleanup carefully. External termination or a nonterminating protected block need not reach finally.
function work() { try { return 7; } finally { console.log("cleanup"); } }console.log(work());Expected output in Node.js:
cleanup7Cleanup executes before the caller receives the pending return.
function choose() { try { return 3; } finally { return 9; } }console.log(choose());Expected output in Node.js:
9An abrupt return in finally overrides the earlier return. This is a cautionary example.
Common mistakes
Avoid returning from finally because it can hide failures or replace intended results.
Practice
Trace a function that returns in try, logs cleanup in finally, and then compare a cautionary overriding return.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript finally: Cleanup and Completion Order — Knowledge Check
Apply the taught concept and predict the output.
What happens to a pending return when finally completes normally?
Can try be paired with finally without catch?
Why avoid return inside finally?
What is the exact console output in JavaScript finally: Cleanup and Completion Order example 1?
function work() { try { return 7; } finally { console.log("cleanup"); } }console.log(work());What is the exact console output in JavaScript finally: Cleanup and Completion Order example 2?
function choose() { try { return 3; } finally { return 9; } }console.log(choose());