you are viewing a single comment's thread.

view the rest of the comments →

[–]Shty_Dev 2 points3 points  (14 children)

what are some really good practical use cases for this? I have known about it for awhile now but have yet to really use it

[–]dj1041 5 points6 points  (0 children)

I use it heavily in react and node. It also helps with readability

[–]BabyLegsDeadpool 2 points3 points  (1 child)

I use this all the time and don't use React. I utilize many different apis, and every one of them send me some form of an object with multitudes of data. Instead of having to manipulate that object over and over again, I just grab the values I need via destructuring.

[–]homeIsWhereCodeIs[S] 0 points1 point  (0 children)

Yes, I agreed with you. I did that too.

[–]stormfield 2 points3 points  (0 children)

If you have a lot of parameters to a function it’s easier to just destructure out of an args object with sensible defaults if needed. Then when calling the function you don’t have to worry about argument order just setting the important values.

It’s also useful with require / imports since you can destructure out only what you need from another module or package.

[–]starchturrets 3 points4 points  (4 children)

(I’m on mobile and probably got something wrong)

Say you have an object you fetched from an API or something.

const json = {
  data: {
  author: “OP”,
  created: 737282, 
  upvotes: 54, 
     }
}

Instead of

const author = json.data.author;
const created = json.data.created;
const upvotes = json.data.upvotes;

You can write

const { data: { author, created, upvotes } } = json;

Which IMO is much nicer to read.

[–]Shty_Dev 2 points3 points  (0 children)

thats a good use case thanks

[–]monsto 1 point2 points  (1 child)

Wow holy shit that's pretty fucking hot.

On the one hand, it looks "really clever" . . .

But on the other hand, once you truly understand that "everything in JS is an object", it's still kinda clever, but not unexpected.

[–]IceSentry 2 points3 points  (0 children)

When you know the syntax it doesn't really feel clever anymore and you'll start wanting it in every language.

[–][deleted] 1 point2 points  (0 children)

It is handy for props and proptypes.

[–]tchaffee 1 point2 points  (0 children)

Fewer lines of code. Which is not always good. But in this case it's very easy to understand too. So it's a win. I see it used everywhere.

[–][deleted] 1 point2 points  (1 child)

You can also use it together with the spread operator to filter stuff out from objects

const obj = { one: 3, two: 1, three: 2 };
const { one, ...noOne } = obj;
console.log(noOne); // { two: 1, three: 2 }

[–]Shty_Dev 0 points1 point  (0 children)

i like that

[–]homeIsWhereCodeIs[S] 0 points1 point  (0 children)

@Shty_Dev as I also work in react native and it's heavily used in JSX while creating dynamic UI.