133

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?

1 Answer 1

266

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Nifty! It seems like setting the defaults on the destructuring side (the way you're doing it) would always be preferred to doing it on the default parameter side (like I was). Would you agree with that? Can you think of anything to watch out for?
I don't think one is "preferred" over the other. It just does something else.
@AlanHamlett No, destructuring only deals with undefined - passing null must be done explicitly, and therefore leads to an error. To deal with both null and undefined, use the standard b == null ? "bar" : b inside the function.
@Bergi Could you explain what the difference between your answer and test({a="foo", b="bar"}) is?
@YonggooNoh See here and here
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.