DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

finally() method in JavaScript

finally is a method utilized within the try-catch construct in JavaScript. It executes after the try and catch blocks, regardless of whether the promise has been fulfilled or rejected. This function's primary role is to perform necessary cleanup tasks and convey a message to the user. A common use case might be to inform the user, 'Your request has been processed', indicating that the operation has concluded, irrespective of its success or failure.

Another best way to understand is
When you have a chunk of code that might cause a problem (an error), you wrap it in a try block. If something goes wrong, instead of breaking everything, the program jumps to the catch block where you can decide what to do.

But what if you want to do something whether or not there was a problem? Maybe you need to clean up, like putting away toys after playtime. Or maybe you want to let the user know that your program is done with its job.

That's where finally comes in. No matter what happens in try and catch, whether there was an error or not, the code in finally will run. It's like saying "no matter what, let's clean up before we go."

Here is a simple example:

try {
    // Code that might go wrong
    console.log("Let's try to do something.");
    throw new Error('Oops! Something went wrong.'); // This line creates an error on purpose
} catch (error) {
    // What to do if there's an error
    console.log('We caught an error: ', error);
} finally {
    // This code runs no matter what
    console.log('Finally, this runs no matter what happens above.');
}
Enter fullscreen mode Exit fullscreen mode

In this example, we try to do something that causes an error. When the error happens, we move to "catch" and handle the error. But no matter what, we then move to "finally", and it logs a message saying 'Finally, this runs no matter what happens above

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/

Top comments (0)