Search code examples
javascriptecmascript-6default-parametersspread-syntax

Using Default Values and Spread Syntax in ES6


While going through features of JavaScript, I used default arguments and spread syntax in same function.

let whatIsThis = (a, b = 2, ...c) => {
    console.log("a = " + a, "b = " + b,"c = " + c)
}

whatIsThis(a = 1, c = [2,3,4,5,6,7,8])

After running it, I expected output to be like this:

"a = 1"
"b = 2"
"c = 2,3,4,5,6,7,8"

But instead I got this:

"a = 1"
"b = 2,3,4,5,6,7,8"
"c = "

Why didn't this worked?


Solution

  • It's because you can't pass named arguments to a function in JavaScript. When you do whatIsThis(a = 1, c = [2,3,4,5,6,7,8]) what it really means is whatIsThis(1, [2,3,4,5,6,7,8]) (because a = 1 statement returns 1).

    What you can do is move default argument to the end (which is generally a good practice) or wrap your arguments in objects. For example

    let whatIsThis = ({a, b = 2, c}) => {
        console.log("a = " + a, "b = " + b,"c = " + c)
    }
    
    whatIsThis({a: 1, c: [2,3,4,5,6,7,8]})