I know this question has been discussed so many times, and I think I got a basic idea. There are some top rated answers I found from StackOverflow:
Let's consider the example below
clone
and clone2
are shallow, only properties of original object are affected. clone3
and clone4
are deep.
However if the spread operator only creates deep copy sometimes, then how can I test if the new object is a deep copy or not?
It creates deep copy in case of clone4
- as long as the depth is controlled by a developer. Generally there's no need to test if an object is deep copy or just different in React, because this check is expensive and requires to traverse nested objects in both compared objects and compare them property by property.
Performance is the reason why React relies on immutability. If a new value isn't ===
equal, it's considered a different value.
So james is a shallow copy in Facebook's code.
It isn't. It's a reference that was assigned to another variable. It's still same object.
Are reference and shallow copy exactly the same thing in JS?
A reference isn't a copy. So it isn't shallow copy, too.
I commented NBAChampion out in clone4, so now NBAChampion is a reference rather than copy! If I push a new value in user.highlights.NBAChampion, clone4 will also updates. What should we call this type of object? It's neither a shallow nor deep copy.
It's just a copy. It doesn't have specific name, because there's rarely a need to do such selective copies. If the intention is to make it act like deep copy, it should be called a mistake.