try{} and catch{} are easy:
- try{} runs code (and prevents script crash on error)
- catch{} handles the error
But finally{} ๐ถ๐ ๐๐ต๐ฒ ๐บ๐ถ๐๐๐ป๐ฑ๐ฒ๐ฟ๐๐๐ผ๐ผ๐ฑ ๐ผ๐ป๐ฒ.
Most people say:
"finally{} always runs after try{} or catch{}."
Correctโฆ ๐ฏ๐๐ ๐ผ๐ป๐น๐ ๐ต๐ฎ๐น๐ณ ๐๐ต๐ฒ ๐๐ฟ๐๐๐ต.
Hereโs the surprise:
You ๐ฑ๐ผ๐ปโ๐ ๐ป๐ฒ๐ฒ๐ฑ finally{} to run code after try/catch in a simple block:
try { console.log(a) }
catch (error) { console.log(error) }
finally { console.log("The End") }
You could just place console.log("The End") after everything.
Soโฆ whatโs the real purpose of finally{}?
๐ง๐ต๐ฒ ๐ฟ๐ฒ๐ฎ๐น ๐ฝ๐ผ๐๐ฒ๐ฟ ๐ฎ๐ฝ๐ฝ๐ฒ๐ฎ๐ฟ๐ ๐ถ๐ป๐๐ถ๐ฑ๐ฒ ๐ณ๐๐ป๐ฐ๐๐ถ๐ผ๐ป๐:
function main() {
try {
return a
} catch (error) {
return error
} finally {
console.log("The End")
}
}
Normally, when a function hits return, the remaining code never executes.
But with finally{}, this line ๐๐๐ถ๐น๐น ๐ฟ๐๐ป๐, even if both try and catch returned.
That's the true magic of finally{} โ
It ๐ฎ๐น๐๐ฎ๐๐ executes, even after a return, making it perfect for cleanup, logs, closing connections, releasing resources, etc.
I was confused about this early on, but once it clicked, it made advanced JS flow much clearer.
๐ฃ๐ฆ: Which JavaScript concept confused you the most when you first learned it?
Top comments (0)