Free email newsletter: “ES.next News

2014-04-23

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:

No comments: