What is copying?
- A copy will look exactly like the original, but it’s not exactly like that. When you change the copy’s data, you would expect that the original would remain the same, only the copy would change.
- In programming, we store values in variables. Making a copy means you create a new variable with the same value. However, there is a very dangerous problem when copying that we must consider carefully: deep copy and shallow copy. A deep copy means that the entire value assigned to the variable will be copied and completely separated from the original. Meanwhile, shallow copy means that some values will still be connected to the original.
There are 3 common ways to copy objects in javascript
1. Use Object.assign method in javascript
2. Copy javascript Spread syntax
3. Use JSON.parse() and JSON.stringify()
Of the three ways to copy objects above, two of them belong to shallow copy, which are Object.assign(), and Spread Operator. And deep copy is the third way – Using JSON.parse() and JSON.stringify().
Shallow copying and Deep copying
- Shallow copy: It simply copies the object’s value, but the nested values still refer to the original object
Reference types in Javascript generally have 3 types: Array, function and object.
Let’s see an example of shallow copy object js using the spread operator
- Deep copy: This guy is the opposite of shallow copy, it copies the object’s value but the reference values in the original object do not change.
Example of deep clone usage using JSON.parse() and JSON.stringify()
- Now we do the same as above, update d = 34, then what happens, see next
=> We see, when update d = 34, the original object has changed but the clone object has not because it is no longer the reference type of the original object.