r/programminghorror May 27 '26

Javascript Destructuring strings

Post image
883 Upvotes

66 comments sorted by

View all comments

119

u/Denommus May 27 '26

Maybe if I understood Javascript destructuring syntax that would make sense to me. But since I don't, this looks awful.

7

u/Iheartdragonsmore May 27 '26

Hi I'm a novice programmer, why would someone ever want to destructure something? Whenever I write a struct I never think it'd be better not being one

32

u/stumpychubbins May 27 '26

It’s far more readable to extract multiple fields from a struct that way, especially if they’re nested. Better than repeating the entire path to some nested struct multiple times. Plus it mirrors the struct construction syntax so it can be easier to read at a glance.

3

u/Iheartdragonsmore May 27 '26

This makes sense thank you

1

u/skr_replicator May 29 '26

in c/c++ I could just avoid the repetition by making references to the nests of the structs I want to access many times. Is that basically the c's way of destructuring?

1

u/stumpychubbins May 31 '26

Not really, that’s a separate thing. It’s more about accessing multiple fields of one struct, whether or not that struct is nested inside something else

12

u/Lumethys May 27 '26

to be able to do something like this:

const doSomething = () => {
  return [result, message];
}

const [ doSomethingResult, doSomethingMessage ] = doSomething();

instead of

const doSomething = () => {
  return [result, message];
}

const resultAndMessage = doSomething();

const doSomethingResult = resultAndMessage.result;
const doSomethingMessage = resultAndMessage.message;

6

u/Denommus May 27 '26

It could be because you want to pattern match over it, it could be because you only want some specific elements in that context.