More and more often I come across code making use of the ES2015 introduced destructuring assignment and even more often I find it very hard to understand what the author is doing. I can see that destructuring can be very useful in some cases but I have the impression that it is often introducing unnecessary code complexity.
E.g. the Nested object and array destructuring example on MDN is using this line do destructure a nested array:
var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
Where is the advantage over something like this, that looks a lot more readable to me:
var englishTitle = metadata.title,
localeTitle = metadata.translations[0].title;
What problems are being solved by destructuring assignments?
When to use them and when not to?
The benefit is that you don't need to repeat the destructured expression. Granted, in your example it hardly makes a difference, as you've already got it neatly in that metadata
variable.
But if it is a very complex expression, or something else, you could save an extra variable. For example, compare this function
function example(metadata) {
var englishTitle = metadata.title,
localeTitle = metadata.translations[0].title;
…; // use englishTitle and localeTitle
}
to
function example({title: englishTitle, translations: [{title: localeTitle}]}) {
…; // use englishTitle and localeTitle
}
and it becomes more obvious how declarative it is.
As it is true for every syntactic sugar: apply it only where it sweetens your code.
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