ES6 Object Destructuring Default Parameters

JavascriptEcmascript 6

Javascript Problem Overview


I'm trying to figure out if there's a way to use object destructuring of default parameters without worrying about the object being partially defined. Consider the following:

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

When I call this with {a: "qux"}, for instance, I see qux undefined in the console when what I really want is qux bar. Is there a way to achieve this without manually checking all the object's properties?

Javascript Solutions


Solution 1 - Javascript

Yes. You can use "defaults" in destructuring as well:

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

This is not restricted to function parameters, but works in every destructuring expression.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3019273View Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow