Sub topic 8
Optional catch Binding
This chapter assumes you already know how try and catch work, how to read an Error's name and message, and how to check a caught error with instanceof and rethrow it. All of that was covered in earlier chapters. Here you will learn a small piece of syntax added in ES2019: a catch clause that has no error variable. You will also learn when that syntax is the right choice and when it hides bugs.
The syntax
Before ES2019, every catch clause needed a parameter in parentheses, even if the code never used it. Developers often wrote catch (e) or catch (_) just to satisfy the grammar. Linters would then warn about an unused variable.
Since ES2019 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 as catch (err) with an unused err. The engine still catches the thrown value and still runs the block. The only difference is that you have no name for the value inside the block.
The parentheses must go away together with the variable. An empty pair of parentheses is a syntax error:
// SyntaxError: Unexpected token ')'
// try { JSON.parse('x'); } catch () { console.log('bad'); }The table below compares the valid forms.
| Form | Valid since | Error available in block |
|---|---|---|
| `catch (err) { ... }` | ES3 | Yes, as `err` |
| `catch ({ message }) { ... }` | ES2015 (destructuring) | Only the destructured properties |
| `catch { ... }` | ES2019 | No |
| `catch () { ... }` | Never | Not valid syntax |
Support
Optional catch binding works in every current browser and in Node.js 10 and later. Chrome 66, Firefox 58, and Safari 11.1 were the first versions to support it. TypeScript and Babel both accept it, and they can compile it down to catch (_unused) for older targets. In practice you can use it in any code written today without thinking about support.
When omitting the binding makes sense
Leave out the variable when two things are both true. First, the outcome you care about is only "it failed". Second, every likely failure in the try block means the same thing to your code.
Validation by attempt
Some APIs only tell you whether input is valid by throwing. JSON.parse is one of them. The URL constructor is another: it throws a TypeError when the string is not an absolute URL.
function isAbsoluteUrl(text) {
try {
new URL(text);
return true;
} catch {
return false;
}
}
console.log(isAbsoluteUrl('https://example.com/path')); // true
console.log(isAbsoluteUrl('/relative/path')); // false
console.log(isAbsoluteUrl('not a url')); // falseIn this function the try block contains a single call, and the only way it can fail is invalid input. The error object adds nothing.
Feature detection
Some environments throw when you touch a feature. Browsers can throw a SecurityError when a page reads localStorage while storage is blocked. Detection code usually only needs a yes or no:
function storageAvailable() {
try {
const key = '__storage_test__';
globalThis.localStorage.setItem(key, key);
globalThis.localStorage.removeItem(key);
return true;
} catch {
return false;
}
}
console.log(storageAvailable());In a normal browser tab this prints true. In Node.js without localStorage, globalThis.localStorage is undefined, so setItem throws a TypeError and the function returns false. Here, "unavailable for any reason" is the correct answer.
Using a fallback value
Sometimes a failure should just produce a default, and the reason really doesn't matter. Reading an optional, user-edited setting is an example:
function parseOptionalNumber(text, fallback) {
try {
const value = JSON.parse(text);
if (typeof value !== 'number') throw new TypeError('not a number');
return value;
} catch {
return fallback;
}
}
console.log(parseOptionalNumber('42', 0)); // 42
console.log(parseOptionalNumber('"42"', 0)); // 0
console.log(parseOptionalNumber('', 0)); // 0When you still need the binding
A bare catch catches everything, and you cannot narrow what it catches. You have no variable to test with instanceof, no code to compare, and nothing to rethrow. Every rule from the previous chapter about handling only what you understand depends on having the error in hand.
Ignoring one specific failure
A common task is deleting a file that might not exist. A missing file is fine. A permissions error is not. You need the error to tell those two cases apart:
const fs = require('node:fs');
function removeIfExists(path) {
try {
fs.unlinkSync(path);
} catch (err) {
if (err.code !== 'ENOENT') throw err;
}
}
removeIfExists('./does-not-exist.tmp'); // no error
console.log('done');If you wrote catch {} here, a permissions failure or a path that points to a directory would disappear silently. Your program would continue as if the file had been removed.
Logging or wrapping
Code that reports the failure needs the error object. That includes logging, wrapping it with cause (covered in the next chapter), and showing it to a user. If any of these happen in the block, keep the binding.
The flowchart below summarizes the decision.
The main gotcha: hiding your own bugs
A bare catch also catches mistakes in your code, not only the failures you planned for. A typo becomes a TypeError or ReferenceError, and the catch block quietly turns it into a normal result.
function getPort(config) {
try {
return config.sever.port; // typo: should be "server"
} catch {
return 3000;
}
}
console.log(getPort({ server: { port: 8080 } })); // 3000, not 8080The author wanted "use 3000 if the config has no server section". What actually happens is that the function always returns 3000, and nothing reports a problem. No error was logged and the code had nothing to check, so the bug can survive for a long time.
You can reduce this risk in two ways:
- Keep the
tryblock as small as possible. Wrap only the single call that is expected to throw, and put the rest of the logic outside the block. - Don't use exceptions for checks that have a direct test. In
getPort, optional chaining expresses the intent without any try/catch:return config.server?.port ?? 3000;.
A related gotcha: destructuring the binding
The table above showed that the binding can be a destructuring pattern. That looks like a neat compromise between a full binding and none at all, but it has a trap. JavaScript can throw any value, including null and undefined. Destructuring those values throws a new TypeError from inside the catch clause itself:
try {
try {
throw null;
} catch ({ message }) {
console.log('handled:', message);
}
} catch (outer) {
console.log(outer.name); // TypeError
}The inner handler never runs. The new TypeError replaces the original thrown value and propagates outward. Code that only ever catches real Error instances is safe, but third-party code sometimes throws strings or null. A plain catch (err) with property access in the body, such as err?.message, handles every value.
Linters and style
ESLint's no-unused-vars rule checks unused catch parameters when its caughtErrors option is "all", which is the default starting in ESLint 9. With that setting, catch (e) with an unused e produces a warning, and the fix is to drop the binding. Some teams prefer the opposite rule: always bind the error so that adding logging later is a one-line change. Either policy is fine as long as the team applies it consistently. What matters is that a bare catch signals "I know the reason doesn't matter here", so reviewers should check that the claim is true.
Summary
catch { ... }(ES2019) catches the thrown value without giving it a name.catch () { ... }is a syntax error.- It fits validation by attempt, feature detection, and fallback values, where any failure means the same thing.
- Without a binding you cannot narrow, log, wrap, or rethrow, so keep
catch (err)whenever any of those matter. - A bare catch also swallows your own
TypeErrors andReferenceErrors. Keep thetryblock small, or avoid try/catch when a direct check exists. - Destructuring in the catch parameter throws if the thrown value is
nullorundefined.
Exercise
A teammate writes function load(raw) { try { const data = JSON.parse(raw); return normalise(data.items); } catch { return []; } }. Explain what risk this carries and rewrite it so that only parse failures fall back to an empty array.
Show answer
The bare catch covers both JSON.parse and normalise, so a bug inside normalise (or a missing items property causing a TypeError) silently returns []. Shrink the try block to the call that is expected to throw: function load(raw) { let data; try { data = JSON.parse(raw); } catch { return []; } return normalise(data.items); }. Now errors from normalise propagate to the caller.
Exercise
Which of these are valid syntax, and what does each print? (a) try { throw 1; } catch { console.log('a'); } (b) try { throw 1; } catch () { console.log('b'); } (c) try { throw undefined; } catch ({ message }) { console.log('c'); }
Show answer
(a) is valid and prints "a". (b) is a SyntaxError because empty parentheses are not allowed, so the script never runs. (c) is valid syntax, but destructuring undefined throws a TypeError before the block runs, so nothing prints and the TypeError propagates.
Exercise
You are writing a function that deletes a temporary directory and should ignore the case where the directory is already gone. Should you use a bare catch? Why or why not?
Show answer
No. You need to tell "already gone" (code ENOENT) apart from other failures such as permission errors, which should not be ignored. That requires the error variable: catch (err) { if (err.code !== 'ENOENT') throw err; }.