Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

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;
    > foo()
    Error: Missing parameter
    > foo(123)
Related reading: