Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 deconstructing nested optional arguments?

Consider the following ES6 code:

function foo({name, address: {street, postcode}}) {
  console.log(name, street, postcode);
}

foo({name: 'John', address: {street: 'Foo', postcode: 1234}});
foo({name: 'Bob'});

The first call works as expected. However, I would like to make address optional (street and postcode would be undefined) instead of throwing an error. Is this possible?

like image 774
Elliot Chance Avatar asked Nov 26 '15 01:11

Elliot Chance


People also ask

What is ES6 destructuring in JavaScript?

ES6 brings with it a bunch of nifty new ways to do things with JavaScript. One of the things I use ALL THE TIME is Destructuring. It allows you to pick and choose properties out of an object and automatically assign them to a variable. Take the following JavaScript Object for example:

How to pass parameters as an object in ES6?

With ES6 you can pass parameters as an object like following code. Note that if sectionItem is omitted, it'll be undefined. As stated in the comments, you could also simply move sectionItem to the end of the function, making it easier to omit. Or, if you need to be ES5 compliant, you can reproduce ES6 behavior by doing something like this.

What are default values in ES6?

Default values are one, nifty way to guard against `undefined` errors in your destructured objects. ES6 is a great improvement to the JavaScript syntax, and Airbnb’s ESLint configuration is an excellent linter to identify code where the latest and greatest in ES6 could be used but hasn’t been.

When should I avoid using an empty nested object literal?

When using nested object destructuring, be careful to avoid using an empty nested object literal. Though it is valid syntax, it actually does no assignment. For example, the following destructuring does absolutely no assignment.


1 Answers

I found the solution:

function foo({name, address: {street, postcode} = {}}) {
  console.log(name, street, postcode);
}
like image 82
Elliot Chance Avatar answered Oct 07 '22 19:10

Elliot Chance