Skip to content

Throw expressions

Baseline logo Baseline
Chrome logo Edge logo
Firefox logo Zen logo
Safari logo
Node logo
Bun logo
Deno logo
Cloudflare Workers logo

Throw errors in expressions.

Type TC39 CoreJS Babel Civet JS+
Syntax Stage 2 View View via Babel
JS+ TypeScript
const double = (x = throw new Error('double expects a number')) => {
return x * 2;
}
double(); // Error: double expects a number
const double = (x: number) => {
if (typeof x !== 'number') {
throw new Error('double expects a number');
}
return x * 2;
}

In JavaScript throw expressions could also be used to throw errors on missing parameters.

const double = (x = throw new Error('double expects a number')) => {
return x * 2;
};
double(); // Error: double expects a number