Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).
10.1.1 Object destructuring
Destructuring objects:
Destructuring helps with processing return values:
10.1.2 Array destructuring
Array destructuring (works for all iterable values):
Destructuring helps with processing return values:
10.1.3 Where can destructuring be used?
Destructuring can be used in the following locations (I’m showing Array patterns to demonstrate; object patterns work just as well):
You can also destructure in a for-of
loop:
10.2 Background: Constructing data versus extracting data
To fully understand what destructuring is, let’s first examine its broader context.
JavaScript has operations for constructing data, one property at a time:
The same syntax can be used to extract data. Again, one property at a time:
Additionally, there is syntax to construct multiple properties at the same time, via an object literal:
Before ES6, there was no corresponding mechanism for extracting data. That’s what destructuring is – it lets you extract multiple properties from an object via an object pattern. For example, on the left-hand side of an assignment:
You can also destructure Arrays via patterns:
No comments:
Post a Comment