What is the optional catch binding in JavaScript?

Overview

In JavaScript, we use the optional catch binding function to skip the error argument of the catch block in a try...catch statement.

Syntax

// try...catch with error arguument
try{
} catch(err) { // error argument is present
}
// try...catch without error arguument
try{
} catch{ // error argument is skipped
}
Optional catch binding

Note: This feature was added in the ES10/2019.

The error argument contains the reason and cause of the exception.

The optional catch binding can be used when we need to handle the error but are not interested in the error's cause.

Example

Let's use the optional catch binding for handing the JSON parse exception.

Console
Using optional catch binding

Explanation

In the above code:

  • Line 8: We parse a string abc as a JSON using the JSON.parse method. However, this will throw an error because it is not a valid JSON string.
  • Line 9: We skip the error argument in the catch block, as it is obvious that if any error occurs it will be due to the invalid JSON data.

Free Resources