Required Arguments

I often find it necessary to have functions with required arguments. As JS defaults arguments to undefined, we need to write code like this.

function required(name) {
  throw new Error(`Required argument "${name}" was not provided!`);

function foo(bar = required("bar") /* ... */) {
  // ...

This is a bit verbose and whenever we rename bar we need to rename the string passed to required().

Proposed Shorthand

function foo(bar! /* ... */) {
  // ...

All arguments before the required argument must also be marked as required.

Thanks, any thoughts?

I see the value in what you're proposing, and it would be nice to have something like that when creating public-facing APIs to ensure people are using them correctly.

And just to throw out another possible solution that can be done today, that allows you to explicitly pass in undefined and simply forbids the wrong number of arguments:

// You can of course extract logic out into a helper function.
function add(x, y) {
  if (arguments.length !== 2) throw new Error('This function requires exactly 2 arguments')
  return x + y
1 Like

As this syntax would only help with missing arguments, functions that still need to check that provided arguments are of the correct type don’t get as much benefit.

Perhaps decorators for parameters would provide more power, to check things like types too. Ref: proposal-decorators/ at cc962f994c5ae3cccabd9808fc6d1b2b9d627713 · tc39/proposal-decorators · GitHub