Object destructuring
What's wrong with this picture?
Nothing of course, the function works properly and does what it needs to. But, imagine you were working with a humongous object filled with all kinds of properties. It would be pretty nice to make this more readable and type-friendly.
Meet Object destructuring
Notice what I've done inside of the function. I've taken all the properties of the object passed through the function(assuming I know what properties will be inside), and destructured them so I can call them without referencing the actual object, since I have already done so. This helps make the code readable, and with a larger object, makes writing out the properties much more convenient.
Still not convinced?
Let me give you an extreme example:
You may come across an object with a value that you need nested very deep, or multiple values that you need. Instead of assigning three variables on three lines and calling all of them individually, you can use the assumed object format and gather them in one line like so:
I've taken the assumed structure of the object and replaced where the values should be with an assigned variable. For the rest of the function I can now play with all of these values after extracting them once. You can also use this assignment in the function parameter:
Hopefully this post has helped and brought something to your attention that I personally find useful. There's a lot more you can do with object destructuring, here's a more thorough breakdown on MDN.
Top comments (0)