Jared Deckard
Jared Deckard

Reputation: 661

ES6 Named Object Parameter Destructuring

I am currently using the object destructuring pattern with default parameters described in that 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 the object parameter without assigning it to a variable in the function body and explicitly listing each key.

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

I tried naming the object argument, but the function looses the ability to resolve missing keys to their default value.

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

It seems to be ignoring the default parameters when destructuring into a named argument.

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


Edit: I removed a superfluous example that did not add context to the question.

Upvotes: 8

Views: 1735

Answers (1)

lonesomeday
lonesomeday

Reputation: 238115

Honestly, I think you're overcomplicating this. Default parameters are not compulsory -- in this case your code can be cleaner without it.

I would simply take the object options as the parameter and do the destructuring within the body of the function, 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


With particular regard to your final snippet:

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

The problem is that a default parameter is used when the value passed is undefined. Here, the value passed is {a: "baz"}. That is not undefined, so the default parameter is ignored. Objects are not merged automatically.

More broadly in answer to your question: there is no way of getting both an object and destructuring some of its properties in the parameters of a method. Frankly, I'm grateful, because function signatures can be hard enough to read at first glance as it is.

Upvotes: 6

Related Questions