Destructuring arrays and objects
Destructuring in JavaScript is an assignment syntax that allows you to conveniently extract data from arrays and objects in one line.
Object destructuringβ
The properties title
, group
and quantity
repeat the structure of the object fruit
and copy their values into identical variables found in {...}
. Therefore, if you swap the variables in {...}
, then the code will work just as well, try swapping the variables in the example above.
Nested objectβ
We can also destructure the nested object.
Other namesβ
If you need to use variable names other than property names, the following syntax will work:
Default valuesβ
If in {...}
you write a property variable which will not be found, then it will be assigned the value undefined
. To assign a default value to a variable , you can assign that value to it. If you try to assign a value to a variable whose properties are found, then the property value will be assigned to it. Let's look at an example.
The title
contains the property value, not what we assign to it. The group
property does not exist in the fruit
object, and we have not assigned any values to the variable . The property quantity
also does not exist, but we assigned the value 5
to the variable .
Remainderβ
If you need to get one variable from an object, and group the rest into another object, then use ...
before the variable from which the object with the remaining properties will be created.
Destructuring arraysβ
Destructuring of an array is the same as for an object. The only difference is that the values of the array elements will be assigned to the variables in the order in which the elements are defined.
Remainderβ
By analogy with objects, the remainder works.
Copy of arrayβ
An example of creating a copy of an array.
Concatenating arraysβ
An example of combining arrays into one.
Problems?β
Write to Discord chat.
Questions:β
Destructuring is it?
- Function
- Syntax
- Object
Is it necessary, when destructuring an object, to put variables in the same order as they are in the object?
- Yes
- No
What will be assigned to a variable if no identical property is found in the object?
error
undefined
unknown
Is the order of elements in an object important when it is destructed?
- Yes
- No
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Linksβ
Contributors β¨β
Thanks goes to these wonderful people (emoji key):
IIo3iTiv | Dmitriy Vasilev π΅ | Resoner2005 π π¨ π | Navernoss π π π¨ |