What is destructuring?
ES6 (more formally known as ES2015) brings a lot of helpful language features
to Javascript. Arrow functions that make writing method functions easier, block scoping via let
, and native support for Promises are some of the features I am most excited about.
Another interesting feature is destructuring, which allows us to extract values from objects and arrays with a more concise syntax.
Array destructuring
The syntax (technically, it is called a pattern
) for destructuring arrays looks like an array itself:
The position of x
is important. If you want to ignore the first element, and only choose the second element, you can add leading comma’s:
Another example of array destructuring:
x
and y
are assigned to the first and second values in the foods
array. The destructuring syntax, [x, y]
, remains on the left side of the assignment, as we are declaring those variables. The right side is the data to destructure.
Combined with the spread
operator, we can also extract certain values while assigning the remaining elements to a variable:
Object destructuring
Extracting values from arrays is cool, but I think the real bread and butter of destructuring is objects.
Similar to array destructuring, the syntax represents the structure we wish to extract data from. Instead of the position of x
being important, it is the name of the key to extract.
Multiple values can be extracted by separating the variables by commas:
Sometimes, you may want to extract from a certain key, but name the variable something else.
We can also use defaults
when extracting data that may not exist:
We can extend object destructuring to parameters of a function.
Conclusion
Destructuring provides a shortcut to do something very common - extract data. Combined with other ES6 language features, our JS code becomes much more concise and readable. There’s many other use cases for destructuring to explore!
I recommend going through the destructuring section of ES6 Katas or reading through Exploring ES6 for more advanced use cases.