Search code examples
ecmascript-6

Best way to have a defined argument follow an argument with default value in ES6?


In ES6 with default value syntax for function parameters, what's the best way to define the 2nd argument while using the default value for the 1st one in a function call?

function test(arg1 = 2, arg2 = 3) {
    return arg1 + arg2;
}

test() // returns 5;
test(undefined, 2) // returns 4; is this the most concise way?

Also, does the second method call work according to the standard? I only tested it with my cross-compiler which just inserts a statement setting the arguments value if it's equal to undefined; not sure if in actual ES6 engines it looks as the way the function was actually called.


Solution

  • What's the best way to define the 2nd argument while using the default value for the 1st one in a function call?

    Yes, passing undefined is the correct way.

    Is this working according to the standard? Not sure if it actually looks at the way the function was called.

    No, undefined is equivalent to a parameter not passed in the arguments list - in both directions. If you explicitly pass undefined, the default initialiser will be run just as if you had passed nothing. If you don't pass anything, all parameters (without defaults) will be assigned undefined just as if you had passed it explictly.
    The only way to distinguish them would be using arguments.length.

    Is this the most concise way?

    Yes. Elisions (like in the array [,,,]) are syntactically invalid in function calls. You could shorten undefined to void 0, but that's not really idiomatic (only a minifier would do this).