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!

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 6 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles