Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “Exploring ES6”
Book, exercises, quizzes
(free to read online)
Logo of newsletter “ES.next news”
Newsletter (free)
Cover of book “JavaScript for impatient programmers”
Book (free online)

Handling required parameters in ECMAScript 6

[2014-04-23] esnext, dev, javascript
(Ad, please don’t block)

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: