I have been reading about Destructuring assignment introduced in ES6.
What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?
Solution 1
What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- MDN
Advantages
A. Makes code concise and more readable.
B. We can easily avoid repeated destructing expression.
Some use cases
1. To get values in variable from Objects,array
2. To combine an array at any place with another array.
3. To change only desired property in an object
4. To create a shallow copy of objects
5. To extract values from parameters into standalone variables
6. To get dynamic keys value from object
7. To build an object from other object with some default values
8. To swap values
9. To get a subset of an object
9.1 subset of an object:
9.2 To get a subset of an object using comma operator and destructuring:
10. To do array to object conversion:
11. To set default values in function. (Read this answer for more info )
12. To get properties such as length from an array, function name, number of arguments etc.
Solution 2
It is something like what you have can be extracted with the same variable name
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment
var [one, two, three] = ['orange', 'mango', 'banana'];
console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: 'John', age: 32};
console.log(name); // John
console.log(age); // 32
Solution 3
The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.
This facilitates reuse by avoid writing getter methods or wrapper functions.
One best example that I found very helpful in particular was on reusing functions that return more data than what is required.
If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json, then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.
