Search code examples
javascriptreact-nativedestructuring

Is it appropriate to do assignment to destructured variables?


I have declared state like this,

 this.state = { filtersEnabled: false}

and later I destructured this object as follows,

let { filtersEnabled } = this.state;

Now, I want to change the value of filtersEnabled,

filtersEnabled = true

when I do console.log(this.state.filtersEnabled), The answer is => false,

But If I change the value as follows

 this.state.filtersEnabled = true

Now if I do when I do console.log(this.state.filtersEnabled), The answer is => true,

What's the problem here,

1.con't we do any assignment to destructured variables? or

2.con't we do any assignment to destructured state variables?


Solution

  • When you are changing the value like this:

     this.state.filtersEnabled = true
    

    You are changing the value of a property. But when you change the value like this:

     filtersEnabled = true
    

    You basically assign a new value to filtersEnabled. There's no longer a reference to the original value.

    Consider this example:

    let a = 1;
    let b = a;
    a++;
    

    Do you expect b to be 2? No, because ++, like += and = are all operators that create a new assignment.

    This is also why we need let for these cases. const would not allow us to make changes.

    This, however, does change both:

    const a = { val: 1 };
    const b = a;
    a.val++;
    

    b points to the same object. We never do a re-assignment of a (this is also why we can use const here), but we do reassign a property of a (and b). So still the same object, but we modified something inside the object.