Search code examples
ecmascript-6default-parametersdestructuring

How to destructuring with default value in ecmascript 6


How can I do destructing with default parameter?

foo function({data, someOptional = 'default'}){
}

How can I use those features of ES6?


Solution

  • You mention that the calls could be either:

    • foo({data:[123]})
    • foo({filterBy:'else'})

    In the second one, you're not passing data which is not optional in the way you declared you're function.

    If data is also optional, you should declare your function this way (specifying data's default value):

    function foo({data=[], someOptional='default'}){}
    

    That way, you'll be able to make the calls you mentioned.

    Though, if you don't wan't to pass any argument at all and rely on the default parameters, you should declare it that way:

    function foo({data=[], someOptional='default'} = {}){}
    

    That way you'll even be able to make this kind of call : foo()