DEV Community

Discussion on: 5 neat JavaScript tips

 
akashkava profile image
Akash Kava

In which way the word "Reassigning destructured variable" is similar to name.first = ... ? The whole purpose of destructuring is not to use member expression name.first. And yes let { name: { first } } = user is the correct way to use desctructering. user is immutable here. It is important to note that we can pass an object to a function which will not change the original object if function is written correctly using destructering. JavaScript compiler can also optimize it by knowing that the function is pure.

Thread Thread
 
vkbr profile image
Vivek B

Destructuring in itself doesn't make it immutable. In the example @akashkava where you re-assigned value to "name" variable and it didn't affect the original object is because the variable of type String (or any other primitives) are immutable and not because it is coming from a destructured object.
Your example is same as

let name = user.name; // string
Enter fullscreen mode Exit fullscreen mode

which makes it immutable because of the data type. @qm3ster 's example showed that destructured values could be mutated which will mutate the origin object.

Destructuring is just syntactic sugar to provide more readability.
const name = user.name is same as const { name } = user