This MDN documentation on destructuring assignment says that "for both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern". Therefore, there should be four types of destructuring syntax:
- Type 1: object destructuring via binding pattern
- Type 2: array destructuring via binding pattern
- Type 3: object destructuring via assignment pattern
- Type 4: array destructuring via assignment pattern
I have read through the MDN documentation page many times, and the page seems to have provided examples only for the first 3 types. Googling doesn’t seem to help either.
What would be an example of Type 4?
Thanks!
Update 1:
For Type 3, MDN provided this example:
// This assigns a to numbers[0] , and b to number[1]
({ a: numbers[0], b: numbers[1] } = obj);
What would be an equivalent example for Type 4? Thanks!
2
Answers
Here are examples of each of the four types you listed:
Type 1: Object destructuring via binding pattern
Type 2: Array destructuring via binding pattern
Type 3: Object destructuring via assignment pattern
Type 4: Array destructuring via assignment pattern
Advanced example for type 4:
To surgically and individually extract each indexed element of an array value using array destructuring with the assignment pattern, do the following:
In this example, we’re destructuring the
numbers
array from theobj
object and assigning its 1st, 3rd, and 5th elements to the variablesa
,c
, ande
respectively. We use elisions between the commas to skip the elements we don’t want to extract.MDN should have explained Type 4 with a clearer and simpler example. Here you go:
Also, JavaScript arrays are just objects with indexed properties, so the above can also be written as the Type 3 format below: