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, catch has error variable Some times, we need to have catch block with unused variable or without variables, This gives compile error before ES10. Es10 introduced optional catch binding which gives flexibility to use try and catch block without error variable bindings. catch error variable is optional in ES10

Configure ESLint for optional catch handling

By default optional catch handling is not enabled, if you used the below code in eslint project application,

try {

} catch {

}

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

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

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

Babel Syntax support.

This new features grammar syntax will not works 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 supported in the following javascript engines and browsers as per V8

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