Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of destructuring assignments in Javascript [closed]

Tags:

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?

like image 663
birnbaum Avatar asked Mar 22 '16 23:03

birnbaum


1 Answers

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.

like image 121
Bergi Avatar answered Oct 10 '22 15:10

Bergi