2 Use Cases of the 'finally' Keyword in JavaScript

The finally keyword is used in two places: synchronous try-catch-finally blocks and asynchronous Promise chains.

Let's look at each of them one by one.

Synchronous try-catch-finally Block

The finally keyword is used in conjunction with a try and catch block to define a block of code that will be executed regardless of whether an exception is thrown or not.

The finally block is often used to contain cleanup code or to ensure that certain tasks are performed regardless of whether an error occurs.

Here's a basic structure of how try, catch, and finally work together:

try {
  // Code that may throw an exception
  // ...
} catch (error) {
  // Code to handle the exception
  // ...
} finally {
  // Code that will always be executed, regardless of whether an exception was thrown or caught
  // This is often used for cleanup operations
  // ...
}

Asynchronous Promise Chain

ES2018 introduced the finally method for promise objects, which serves a similar purpose as the finally clause in a try-catch-finally statement.

finally keyword is used to specify a callback function that will be executed after the Promise is settled, whether it's resolved or rejected.

If you need to perform cleanup tasks, such as closing open files or network connections, regardless of the promise's outcome, a finally callback is the perfect place to do so.

This callback does not receive any arguments, so you cannot determine whether the promise was fulfilled or rejected.

Here's an example of how finally can be used in a Promise chain:

somePromiseReturningFunction()
  .then((result) => {
    // Code to handle the resolved value
    console.log(result);
  })
  .catch((error) => {
    // Code to handle the rejected value
    console.error(error);
  })
  .finally(() => {
    // Code that will be executed regardless of whether the Promise is resolved or rejected
    console.log("Finally block executed");
  });

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda