What is the finally block?
The finally block runs after try/catch, whether or not an error occurred.
Always runs — used for cleanup like closing connections, hiding a loader, or releasing resources.
Runs regardless — executes even if try returns or catch rethrows.
Don't return from finally — it can override a value or swallow an error from try/catch.
async function fetchData(url) {
showLoading();
try {
const response = await fetch(url);
const data = await response.json();
displayData(data);
return data;
} catch (err) {
displayError(err.message);
return null;
} finally {
hideLoading(); // ALWAYS runs, even after return!
}
}
// finally runs even with return
function test() {
try {
return 'from try';
} finally {
console.log('finally runs!'); // Still executes!
// If finally also has return, it overrides try's return
}
}
console.log(test()); // Logs 'finally runs!', returns 'from try'hideLoading always runs: after success (data displayed), after error (error displayed), and even after return statements. The finally block is the last thing to execute.
If finally has its own return, it overrides the try/catch return (avoid this — it is confusing).
finally runs ALWAYS — after success, after error, even after return. The most practical use: loading indicator (show before try, hide in finally).
Know that finally's return overrides try/catch's return (bad practice to return from finally).