Sub topic 8
Optional catch Binding
This chapter assumes you know how try and catch work and how to check an error with instanceof before rethrowing it. Here we look at a small piece of syntax added in ES2019. It lets you write a catch clause without naming the error.
The Syntax
Before ES2019, every catch clause had to declare a variable, even if the code never read it:
function isValidJsonOld(text) {
try {
JSON.parse(text);
return true;
} catch (unused) {
return false;
}
}Linters often flag unused as a variable that is never read. With optional catch binding you can leave out the parentheses and the variable completely:
function isValidJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
console.log(isValidJson('[1, 2]')); // true
console.log(isValidJson('{oops}')); // falseThe behavior is the same. The error is still caught, and the catch block still runs. The only difference is that no variable holds the error. You also have no way to get at it later in that block.
When It Fits
Optional binding makes sense when the fact that the code failed matters more than the reason it failed. Common cases:
- Validation checks that answer yes or no, like
isValidJsonabove. - Feature detection, where a failure tells you the environment lacks a feature.
- Best-effort work with a safe fallback, such as reading a cached value that might be missing or corrupt.
function readCachedNumber(raw, fallback) {
try {
const value = JSON.parse(raw);
return typeof value === 'number' ? value : fallback;
} catch {
return fallback;
}
}
console.log(readCachedNumber('42', 0)); // 42
console.log(readCachedNumber('garbage', 0)); // 0
console.log(readCachedNumber('"text"', 0)); // 0The Common Error: Catching Bugs by Accident
A bare catch catches every error the try block throws, and with no binding you cannot narrow it with instanceof. So a typo in your own code gets swallowed in the same way as bad input:
function isValidJsonBuggy(text) {
try {
JSON.prase(text); // typo: throws TypeError, not SyntaxError
return true;
} catch {
return false;
}
}
console.log(isValidJsonBuggy('[1, 2]')); // false, even for valid JSONThe TypeError ("JSON.prase is not a function") lands in the same catch as a real parse failure. The function returns false for every input, and nothing is logged.
Two habits reduce this risk:
- Keep the
tryblock as small as possible. Put only the call that is expected to fail inside it. - If the block could fail for more than one reason, bind the error and check its type. Then rethrow anything you did not expect.
function isValidJsonStrict(text) {
try {
JSON.parse(text);
return true;
} catch (err) {
if (err instanceof SyntaxError) return false;
throw err;
}
}Choosing Between the Two Forms
| Situation | Form to use |
|---|---|
| A single call whose only failure mode is the one you expect | `catch { ... }` |
| You need to log, inspect, or wrap the error | `catch (err) { ... }` |
| The block could throw for several unrelated reasons | `catch (err)` with `instanceof` and rethrow |
Compatibility
Optional catch binding works in all current browsers and in Node.js 10 and later. If you have to support older engines, a transpiler such as Babel rewrites it into the older form with a named variable.
Exercise
A teammate writes try { const cfg = loadConfig(); applyTheme(cfg.theme); } catch { useDefaultTheme(); }. Why is this risky, and how would you change it?
Show answer
The bare catch handles every error in both calls. A bug in applyTheme, such as a TypeError, gets hidden in the same way as a missing config, and the user silently gets the default theme. Shrink the try block to just loadConfig(), or bind the error, handle only the expected type (for example a custom ConfigNotFoundError), and rethrow everything else.
Exercise
Rewrite try { new URL(input); return true; } catch (e) { return false; } using optional catch binding. Is the bare form safe here?
Show answer
try { new URL(input); return true; } catch { return false; }. It is reasonably safe because the try block contains one call, and the URL constructor throws only a TypeError for invalid input, which is exactly the failure being tested.