ES6 destructuring function parameter - naming root object

Personally I'd rather destructure within the function body, but for completeness I wanted to show that it's technically possible to access both the "root" object and destructured properties via parameters.

To do we take advantage of the fact that parameters have access to preceding parameters in their default values. That allows you to define a second parameter that destructures the first one:

var setupChildClass6 = (options, {minVal, maxVal}=options) => {
    rangeSlider.setup(minVal, maxVal);
    setupParentClass6(options);
};

So this function takes two arguments and defaults to using the first value of the first argument for the second argument.

Of course you'd have to take great care that it's communicated properly what the purpose of this is.


You cannot do it directly in the arguments, but you can extract the values afterward:

function myFun(allVals) {
    const { val1, val2, val3 } = allVals;
    console.log("easy access to individual entries:", val2);
    console.log("easy access to all entries:", allVals);
}

I have the 'options' arguments on too many places myself. I would opt for 1 extra line of code. Not worthy in this example, but a good solution when having destructuring on more lines.

const setupChildClass6 = options => {
    const {minVal, maxVal} = options;
    rangeSlider.setup(minVal, maxVal);
    setupParentClass6(options); 
};

You cannot use destructuring and simple named positional argument for the same parameter at the same time. What you can do:

  1. Use destructuring for setupParentClass6 function, but old ES6 approach for setupChildClass6 (I think this is the best choice, just make name shorter):

    var setupChildClass6 = (o) => {
      rangeSlider.setup(o.minVal, o.maxVal);
      setupParentClass6(o); 
    };
    
  2. Use old arguments object. But arguments can slow down a function (V8 particular), so I think it's a bad approach:

    var setupChildClass6 = ({minVal, maxVal}) => {
      rangeSlider.setup(minVal, maxVal);
      setupParentClass6(arguments[0]); 
    };
    
  3. ES7 has proposal for rest/spread properties (if you don't need minVal and maxVal in setupParentCalss6 function):

    var setupChildClass6b = ({minVal, maxVal, ...rest}) => {
      rangeSlider.setup(minVal, maxVal);
      setupParentClass6(rest);
    };
    

    Unfortunately it's not ES6.