DEV Community

Cover image for ๐— ๐—ผ๐˜€๐˜ ๐˜๐—ฒ๐—ฎ๐—ฐ๐—ต๐—ฒ๐—ฟ๐˜€ ๐——๐—ข๐—กโ€™๐—ง ๐—ธ๐—ป๐—ผ๐˜„ ๐˜๐—ต๐—ถ๐˜€ ๐—ฎ๐—ฏ๐—ผ๐˜‚๐˜ ๐—๐—ฎ๐˜ƒ๐—ฎ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜'๐˜€ finally {} ๐—ฏ๐—น๐—ผ๐—ฐ๐—ธ...
~ Umair Shakoor
~ Umair Shakoor

Posted on

๐— ๐—ผ๐˜€๐˜ ๐˜๐—ฒ๐—ฎ๐—ฐ๐—ต๐—ฒ๐—ฟ๐˜€ ๐——๐—ข๐—กโ€™๐—ง ๐—ธ๐—ป๐—ผ๐˜„ ๐˜๐—ต๐—ถ๐˜€ ๐—ฎ๐—ฏ๐—ผ๐˜‚๐˜ ๐—๐—ฎ๐˜ƒ๐—ฎ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜'๐˜€ finally {} ๐—ฏ๐—น๐—ผ๐—ฐ๐—ธ...

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") }
Enter fullscreen mode Exit fullscreen mode

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")

 }

}
Enter fullscreen mode Exit fullscreen mode

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)