Why use the JavaScript spread operator to update an item in an array?

Viewed 66

I'm just following an online course and I'm interested as to why the tutor would have used the spread operator to update an object in an array instead of just using the object itself?

I've googled it and finding tones of information on the spread operator but not really why he went about it that way.

For example:

handleUpdate = async (post) => {
   post.title = "Updated";
   ...
   const posts = [...this.state.posts];
   const index = posts.indexOf(post);

   // why use this
   posts[index] = { ...post };

   // instead of 
   // posts[index] = post;

   this.setState({ posts });

};

I've tested with the object being set directly and it seems to work but I'm interested as to why you would use one method over the other? It is just a preference thing or it there more to it?

Thanks.

3 Answers

The main reason I can see for this is to create a shallow copy of the object, so that if you perform any operations on the copy, it won't mutate the original. This would be especially useful in a functional programming paradigm where you don't want to mutate any shared objects/maintain a shared state.

However, as I mentioned, this only creates a shallow copy (as opposed to a deep copy), so that if any of the properties of the object are themselves mutable (such as an array property), then those properties would still be able to be mutated.

Edit: From the question in the comments, and building off of what @AdiH mentioned in their answer, it doesn't seem to make any sense to update post.title before creating the shallow copy as this would mutate the original object. It's possible that the author intended for this change to be reflected in both the original and the copy, but for any further changes to be reflected only in the copy

const x = { a: 'b', c: 'd', d: [] };

const copy = { ...x };
copy.a = 'c';
console.log(x); // unchanged

const same = x;
same.a = 'c';
console.log(x); // changed

copy.d.push('e');
console.log(x); // x.d has been changed

I can see your confusion. I think the example is not great. One can only guess what the author had in mind but if he or she intended to enforce immutability I would not have done post.title = "Updated" since it obviously mutates post.

Instead I would have done post[index] = { ...post, title: "Updated"} see examples of JS Spread syntax.

So yes, I'm also unable to guess the motivation behind that example.

The reason deals with the pattern of immutability. Nothing is mutated, rather a new object is created and that object is changed. It makes change detection simple.

However it's not always necessary if developer is careful.

Related