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.
x=[1,2,3];y=[...x];z=x;y[1]=0;z[1]=5;console.log(x===y,x===z, x, y, z)