Optional Catch Binding in JavaScript
🤔 What is Optional Catch Binding?
Introduced in ES2019 (ES10), the Optional Catch Binding feature allows you to omit the error variable in a catch block if you don't need it.
This makes the syntax cleaner when you’re not using the error object inside the catch block.
💡 Before (Traditional Syntax)
Code Snippet
try {
// code that might throw
} catch (error) {
console.log("An error occurred");
}✅ After (Optional Catch Binding)
Code Snippet
try {
// code that might throw
} catch {
console.log("An error occurred");
}Note
You can only omit the error parameter if you don't plan to use it.
📦 Real-World Example
Useful when you're retrying something and don’t need the error message:
Code Snippet
try {
fetchData();
} catch {
retryFetch();
}🚫 Common Mistake
Code Snippet
try {
someInvalidCode();
} catch (err) {
// ❌ Declared 'err' but not using it
}This will still work, but the variable is unnecessary. You can simply do:
Code Snippet
try {
someInvalidCode();
} catch {
// ✅ Clean and modern
}📚 Browser Support
Supported in all modern browsers and environments (Chrome 73+, Node.js 10+, etc.). Not available in IE.
✅ When to Use
- When you don’t need to examine or log the error
- To keep code tidy and minimal
>>“Less is more — especially when it comes to clean code.”