JS: Objects
Theory: Destructuring
Objects in real-world applications often have a complex structure. Objects nested in objects nested in objects, and so on. It isn't convenient to use deeply nested objects directly if you need to access it repeatedly:
Developers try to reduce such code and create intermediate constants for nested data:
The more calls there are to nested data, the more useful this technique is. But data extraction itself can become cumbersome if there is a lot of data. An example from real life:
This is data from a fictional application represented in the jsonapi format. It's used, for example, on Hexlet for interaction between the server and client parts of the site. This data is extracted and displayed within the client. Imagine what the code for extracting the innards of this structure could look like:
The more data you need to get and the deeper it's located, the more monotonous and repetitive code you have to write. There's nothing particularly wrong with this — everyone used to do it this way. But as the language evolved, it became possible to write much better code.
Destructuring is a special syntax that allows you to extract parts of compound data. This is a handy way to break down objects into parts. It allows you to shorten the code and make it more understandable.
Destructuring bears similarities to creating an object. It uses precisely the same syntax, but instead of creating an object, it breaks it down into parts. Destructuring allows you to "break down" an object piece by piece, i.e., you don't have to extract it all at once. The object has three properties in the example above, but only two are retrieved. The order of properties is not important when extracting.
You can also rename when destructuring. This is necessary if a constant with the same name has already been defined above.
If there are no properties in the object, destructuring allows you to set default values for such properties:
Destructuring can be nested. It allows you to extract parts of objects at any depth. Therefore, our example above can be rewritten as follows:
The spread operator has a similar but inverted operator called rest. It can be used during destructuring to collect all the remaining properties into one object:
Although destructuring is optional and does not affect the architecture of your programs, it makes the code cleaner and clearer (if you don't go too far with this).

