Handling required parameters in ECMAScript 6

In ECMAScript 5, you have a few options for ensuring that a required parameter has been provided, all of which are somewhat brittle and inelegant:

function foo(mustBeProvided) {
if (arguments.length < 1) throw new Error(...)
if (! (0 in arguments)) ...
if (mustBeProvided === undefined) ...
}

In ECMAScript 6, you can (ab)use default parameter values to achieve more concise code (credit: idea by Allen Wirfs-Brock):




/**
* Gets called if a parameter is missing and the expression
* specifying the default value is evaluated.
*/
function throwIfMissing() {
throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
return mustBeProvided;
}

Interaction:

> foo()
Error: Missing parameter
> foo(123)
123


Related reading:

Comments

Popular posts from this blog

Steve Lopez and the Importance of Newspapers

A Treasure Hunt Without The Treasure

Drop a ping-pong ball in the clown’s mouth