Codementor Events

Enforcing Required Function Arguments in ES6 JavaScript

Published Aug 15, 2018

Without ES6:

Prior to ES6, JavaScript developers had to do some manual explicit coding to handle missing function arguments. For example, a function with two arguments that are strictly required might have been written like this:

function foo (ham, eggs) {
  if (!ham) throw new Error("ham is a required argument");
  if (!eggs) throw new Error("eggs is a required argument");
  
  // Perform function logic
}

With ES6:

Now, with the advent of ES6, we can leverage default argument values to make this a bit cleaner and condensed:

function foo (ham = isRequired("ham"), eggs = isRequired("eggs")) {
  // Perform function logic
}

function isRequired (argumentName) {
  throw new Error(`${argumentName} is a required argument.`);
}

Since default argument value expressions are only executed when necessary (i.e. the argument is missing or undefined), we can use such a pattern to abstract away the required argument handling. Super clean! Here is the result:

foo();
// Error: ham is a required argument.

foo(undefined);
// Error: ham is a required argument.

foo(null);
// Error: eggs is a required argument.

foo(123, undefined);
// Error: eggs is a required argument.

foo(456, "hold the eggs");
// No errors!
Discover and read more posts from Aaron Hanson
get started
post commentsBe the first to share your opinion
Oren Mizrahi
6 years ago

That is a neat trick.

Hamid Tondkaran
6 years ago

Thank you for the article, but there’s a mistake in the examples:

foo(null, null) wont throw any errors.

because null is not undefined and default props only kick in when the argument is === undefined.

Aaron Hanson
6 years ago

Yes, I clearly mention that this detects only missing or undefined arguments. Null is a valid argument in many cases.

Aaron Hanson
6 years ago

Also foo(null, null) is not one of the examples I provided.

Show more replies