How to fail function calls with undefined arguments with a one-liner (sorta)
- Published at
- Updated at
- Reading time
- 1min
I've been writing JavaScript for so long that I sometimes don't see its quirks. To be fair, there are fewer quirks than ten years ago, but some things would still make great language additions. One thing that would make a lot of sense is required function parameters.
Assume you have a function that defines required arguments. And you really really want to make sure the function is called with the correct arguments by throwing an error.
Here's what you might do:
function doSomethingWithAThing(theThing) {
if (typeof theThing === "undefined") {
throw new Error("theThing is required");
}
}
That's quite a bit of code for such a simple thing.
Unfortunately, you can't do something like this in JavaScript ...
function doSomethingWithAThing(
theThing = throw new Error("theThing Is Undefined")
) {
// ...
}
... because JavaScript doesn't like it.
Peter Kröner published a handy snippet that he carries around from project to project. The post is in German, so here's the English gist of it.
First, define a fail
function.
function fail(reason, ErrorConstructor = Error) {
throw new ErrorConstructor(reason);
}
And second... use it. 🫣
By restructuring the code and transforming the error throwing portion into an expression, you can immediately throw in case a function is called without the required parameters.
function doSomethingWithAThing(
theThing = fail('theThing Is Undefined')
) {
// ...
}
What a beautiful sort of one-line workaround.
Thanks Peter!
Join 5.4k readers and learn something new every week with Web Weekly.