Does Object destructing work by reference or it clones the object

Viewed 3974

I need to copy an object from this.state to change some of its property values.

For example in the following method state is being mutated directly (this.state.errors = {})

   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };

To avoid this, I know that we can use :

a) The object spread operator

let errors={...this.state.errors};

b) Or Object.assign

let errors=Object.assign({},this.state.errors);

But sometimes I've seem some examples in which object destructuring it is used like this:

authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };

So my question is , is it object destructuring equivalent to the other two methods mentioned above? I mean, will I avoid mutating the state directly by using simple object destructuring ?

2 Answers
Related