top | item 33129507

(no title)

julian37 | 3 years ago

All of the examples show a single use but the value of destructuring becomes more obvious when you look at an example with multiple uses. Take this variant of one example:

const Component = (props) => { funcA(props.a.deeply.nested.variable); funcB(); funcC(props.a.deeply.nested.variable); };

Depending on what the functions are doing, neither the VM nor tsc might be able to infer that variable's value stays the same or that props, props.a, props.a.deeply, or props.a.deeply.nested will stay the same for that matter.

The VM will likely have to generate code to dereference the chain all over for the second use, and the compiler might lose narrowing information. Both of these can easily be avoided with destructuring.

(You could use "const variable = props.a.deeply.nested.variable", but then you have many of the same issues the article complains about.)

discuss

order

No comments yet.