DEV Community

Cover image for Exploring Destructuring in JavaScript

Exploring Destructuring in JavaScript

Debajyati Dey on June 21, 2024

What is Destructuring? Destructuring is a special really cool syntax feature in JavaScript, which lets us to extract values from arrays,...
Collapse
 
mikhaelesa profile image
Mikhael Esa • Edited

I was a huge fan of destructuring as it gives me a more concise looking code. But when things get big and many objects are destructured, everything is just losing its context. Take this example

const { prop } = obj
const myObj = obj

// You might have to check to which object this prop belongs to, or even you might not realize if it's a property of an object.
console.log(prop)

// You know immediately that prop belongs to myObj
console.log(myObj.prop)
Enter fullscreen mode Exit fullscreen mode

Not mentioning if you have a colliding property names then you have to make an alias for the colliding property name so you would still ended up in a messy code

Collapse
 
ddebajyati profile image
Debajyati Dey

Understood! I shall keep this in mind.

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN

When using the spread syntax to copy objects that have nested properties, it is crucial to understand how JavaScript handles references to these nested properties. The spread operator creates a shallow copy of the object. This means that while the top-level properties are copied, any nested objects or arrays are still referenced from the original object. Consequently, changes to nested properties in the copied object will also reflect in the original object and vice versa.

Let's take an example:

const person = {
    name: 'John',
    age: 30,
    address: {
        city: 'New York',
        zip: '10001'
    }
};
Enter fullscreen mode Exit fullscreen mode

Here, we define an object person with properties like name, age and address. And address object contains city and zip.

Shallow Copy with Spread Operator

const personCopy = { ...person };
Enter fullscreen mode Exit fullscreen mode

The spread operator { ...person } creates a shallow copy of person. This means that the top-level properties (name, age, and address) are copied directly into personCopy. However, since address is an object (a nested property), only the reference to this object is copied, not the actual nested object itself.

Modifying Nested Property

personCopy.address.city = 'Los Angeles';

console.log(person.address.city); // "Los Angeles"
console.log(personCopy.address.city); // "Los Angeles"
Enter fullscreen mode Exit fullscreen mode

Since personCopy.address is a reference to the same address object as person.address, changing personCopy.address.city to 'Los Angeles' affects both person and personCopy. Hence, both console.log statements output "Los Angeles".

Modifying Nested Property Again

person.address.city = 'New York';

console.log(person.address.city); // "New York"
console.log(personCopy.address.city); // "New York"
Enter fullscreen mode Exit fullscreen mode

Similarly, when we change person.address.city back to 'New York', it also affects personCopy.address.city because they reference the same address object. As a result, both console.log statements output "New York".

Collapse
 
ddebajyati profile image
Debajyati Dey

Massive! That's a brief write up! I learnt something new.
Thank you 😊!

Collapse
 
matin_mollapur profile image
Matin Mollapur

really comprehensive guide on destructuring in javascript! the examples are clear and cover a wide range of use cases, from basic object and array destructuring to more advanced techniques like nested destructuring and using destructuring in function parameters. the section on spread syntax and default values is particularly helpful. thanks for making these concepts so accessible! looking forward to more articles like this.

Collapse
 
ddebajyati profile image
Debajyati Dey

Thank you for your detailed feedback! Pleased to know that you found the guide comprehensive and the examples clear. Looking forward to bringing you more useful content!
And hey!
Thanks again 🙃 for your support!

Collapse
 
swapnoneel123 profile image
Swapnoneel Saha

Really well-explained!!

Collapse
 
ddebajyati profile image
Debajyati Dey

Thanks a lot for your positive feedback! I’m always looking to improve.

Collapse
 
anonsols profile image
Anon Sols

This is amazing, I should also consider writing.

Collapse
 
ddebajyati profile image
Debajyati Dey • Edited

Thank you so much! 😊
Writing is incredibly rewarding, and I'd love to see what you come up with. Let me know if you need any suggestions on getting started, don't hesitate to reach out!

I'd love to read what you write—go for it!

Collapse
 
darshanraval profile image
Darshan Raval

awesome :)

Collapse
 
ddebajyati profile image
Debajyati Dey

Thank u for the appreciation :)

Collapse
 
muhammadanas8 profile image
MuhammadAnas8

Well explained... It was really helpful for me

Collapse
 
ddebajyati profile image
Debajyati Dey

Thank you! It’s great to hear that you've found the explanation helpful!

Collapse
 
sammaji15 profile image
Samyabrata Maji

Great article!!
Would love to know the performance overhead of destructuring. As js devs, we don't really care abt minor performance issue, but still it would be interesting to know.

Collapse
 
ddebajyati profile image
Debajyati Dey

Thank you for your kind words. You asked so I did a quick research on this topic.
I didn't actually thought about the performance consideration before. Well, it is indeed a critical point to think about.

Well as I far as I realised, Destructuring in JavaScript does introduce a slight performance overhead compared to traditional property access (dot notation) due to the extra steps involved in creating and assigning variables. In scenarios where performance is critical, this overhead can become noticeable.

For instance:

  • Server Request Handling: When handling a large number of simultaneous requests, every microsecond counts. Extensively using destructuring in request processing functions can introduce slight delays.
  • WebSocket Data Processing: In a WebSocket server processing high-frequency messages, avoiding destructuring might help reduce overhead.
  • Game Development Loop: In game development, the render loop runs many times per second. Using destructuring could add unnecessary overhead.
// Traditional property access
function updateGameState(state) {
    const x = state.player.x;
    const y = state.player.y;
    // update game state
}

// Destructuring
function updateGameState(state) {
    const { x, y } = state.player;
    // update game state
}
Enter fullscreen mode Exit fullscreen mode
  • Real-time Data Processing: In applications like live data feeds or stock tickers, every bit of performance optimization helps.

There could be more examples. But I think these are enough.

But for most practical purposes, the performance difference is negligible and should not deter you from using destructuring.

As you have been developing applications in JavaScript long before I started, you might know all of this better than I do.

Collapse
 
easywork01 profile image
Pranjal Raj

Great! Loved it

Collapse
 
jon_baso_1c15e0334291a1dc profile image
Jon Baso

All the lightbulbs went off above my head when you tied destructing and imports. Thank you!!!!

Collapse
 
ddebajyati profile image
Debajyati Dey

😊 🙌 😊 🙌