ES6 Triggered Object Parameter Destructuring

I am currently using the object destructuring pattern with default parameters described in this answer to ES6 Object Destructuring Default Parameters .

(function test({a = "foo", b = "bar"} = {}) {
  console.log(a + " " + b);
})();

      

I would like to be able to access a parameter of an object without assigning it to a variable in the body of the function and explicitly listing each key.

(function test({a = "foo", b = "bar"} = {}) {
  const options = {a, b};
  console.log(options);
})();
      

Run codeHide result


I tried calling the object argument, but the function loses the ability to resolve missing keys by default.

(function test(options = {a = "foo", b = "bar"} = {}) {
  console.log(options);
})();
      

Run codeHide result


Seems like defaults are being ignored when destructuring into a named argument.

Is this part of the ES6 specification? Is there a way to achieve the desired behavior without additional code in the function body?


Edit: I removed an extra example that didn't add context to the question.

+3


source to share


1 answer


To be honest, I think you are too insulting. The default parameters are optional - in that case, your code can be clean without it.

I would just take an object options

as a parameter and do the destructuring inside the function body after assigning default values.

function test(options) {
    options = Object.assign({a: 'foo', b: 'bar'}, options);
    let {a, b} = options;
    console.log(options, a, b);
}

test(); // foo bar
test({a: 'baz'}); // baz bar
test({b: 'fuz'}); // foo fuz
test({c: 'fiz'}); // foo bar
      

Run codeHide result





As for your final snippet:

(function test(options = {a: "foo", b: "bar"}) {
  console.log(options);
})({a: "baz"});
      

Run codeHide result


The problem is that the default parameter is used when the value passed undefined

. Here is the passed value {a: "baz"}

. It is not undefined

, so the default is ignored. Objects are not automatically combined.

More broadly, the answer to your question is, there is no way to get both an object and destroy some of its properties in method parameters. To be honest, I am grateful, because function signatures can be complex enough to read at first glance as they are.

+4


source







All Articles