Signup/Sign In
PUBLISHED ON: AUGUST 27, 2021

JavaScript Optional Catch Binding

In earlier versions of JavaScript, it is necessary to pass an exception variable to the catch statement whether needed or not. To avoid this, the optional catch binding was introduced.

The Optional Catch Binding is a new feature in JavaScript introduced by the ECMAScript 2019 (ES10).

The Optional Catch Binding allows us to use the try/catch statement without passing the error parameter inside the catch block. It is optional for you whether you want to pass the error variable or not.

Let's understand it with the help of an example.

Example: Without Optional Catch Binding

Here, we have to pass a variable in the catch block.

//Without optional catch binding

try {
// do something
} catch (error) {
// we have error parameter to handle it
}

Example: With optional catch binding (ES10)

Here, we are free to skip to pass variables in the catch block.

//With optional catch binding

try {
// do something
} catch {
// no binding or parameter to handle it
}

As we can see in our first example, an exception parameter error is passed to the catch statement.

This parameter is used to identify which type of error occurs within the try block. While, in the second example, as we have noticed, there is no parameter passed to the catch statement because it is optional in ES10.

It is helpful if you don't need the exception object in the code that handles the exception.

Example: Optional Catch Binding

In this example, we have demonstrated the use of try and catch blocks with and without exception variables.

<!DOCTYPE html>
<html>
<head>
<title>Optional catch binding</title>
</head>
<body>
	<script type="text/javascript">
	//Wihout optional catch binding
	try {
		throw new Error("Some random error");
	} catch (error) {
		console.log(error)
	}

	//With optional catch binding
	try {
		throw new Error("Hey");
	} catch {
		console.log("No parameter for catch");
	}
	</script>
</body>
</html>

Output

output

Conclusion

In this article, we have learned optional catch binding, which was introduced in ECMAScript 2019 or ES10. It allows us to use the catch block with or without passing the exception variable to the catch statement.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight