Optional Catch binding JavaScript

In JavaScript, you have to use try, catch(or finally) block to handle the exceptions.

An example

try{
//javascript line of code}
catch(error){
//code to handle exception
}
finally {
  //clean up code
}

As you can see above example, the catch has an error variable Sometimes, we need to have a catch block with unused variables or without variables, It gives compile error before ES10.

Es10 introduced optional catch binding, which allows the use of try and catches blocks without error variable bindings. Catch error variable is optional in ES10

Configure ESLint for optional catch handling:

Optional catch handling is not enabled by default. if you used the below code in the ESLint project application,

try {

} catch {

}

You will get compilation errors like Parsing error: Unexpected token { You have to enable the ESLint rule to make it work

You have to make the ES version as 10 in .eslintrc.json as follows.

{
    "parserOptions": {
        "ecmaVersion": 10
    }
}

Babel Syntax support.

This new feature’s grammar syntax will not work with older browsers, To support this, babel is required to compile the new syntax for this feature. Babel provides two plugins to parse and transfer the syntax.

  • plugin-syntax-optional-catch-binding - to parse the new syntax
  • plugin-proposal-optional-catch-binding - parse the syntax and convert the syntax to polyfill old browsers

Configure babel plugin in nodejs projects using npm or yarn

npm install --save-dev @babel/plugin-proposal-optional-catch-binding
yarn add @babel/plugin-proposal-optional-catch-binding --dev

.babelrc

{
  "plugins": ["@babel/plugin-proposal-optional-catch-binding"]
}

Supported versions

This feature is supported in the following javascript engines and browsers as per V8

  • V8 6.6
  • Node10+
  • Chrome66+
  • Firefox 58+
  • Opera 53+
  • Safari 11.1+