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?
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:
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.
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 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.
I found the solution:
function foo({name, address: {street, postcode} = {}}) {
console.log(name, street, postcode);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With