You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A deep copy means that "all of the values of the new variable" are copied and disconnected from the original variable. It makes a copy of all the members of X, allocates different memory location for Y and then assigns the copied members to Y to achieve deep copy. In this way, if X vanishes Y is still valid in the memory.
3016
+
A shallow copy means that certain (sub-)values are still connected to the original variable. It is primarily utilized for copying One Dimensional array elements, where it only copies the elements present at the first level.
3017
+
3018
+
A deep copying means that value of the new variable is disconnected from the original variable
3019
+
while a shallow copy means that some values are still connected to the original variable.
3020
+
3021
+
addresses of X and Y will be the same i.e. they will be pointing to the same memory location.
3011
3022
3023
+
To copy an object in JavaScript, you have three options. Both spread (...) and Object.assign() perform a shallow copy while the JSON methods carry a deep copy.
3024
+
--->Assignment operator “=”
3025
+
--->Use the spread (...) syntax
3026
+
--->Use the Object.assign() method
3027
+
--->Use the JSON.stringify() and JSON.parse() methods --where the stringify() method converts a particular JavaScript object to a string, and then the parse() method performs the parsing operation and returns an object.
3012
3028
3029
+
For a primitive value, you just simply use a simple assignment:The important takeaway here is that you can quickly copy a primitive data type’s exact value
3030
+
in a separate memory space by creating and assigning another variable to the variable being copied. Take note of how it is instantiated — const will not
3031
+
allow later changes.
3013
3032
3033
+
let counter = 1;
3034
+
let copiedCounter = counter;
3035
+
copiedCounter = 2; //And when you change the value of the copied variable, the value of the original remains the same.
3036
+
console.log(counter);
3037
+
Output: 1
3038
+
3039
+
3040
+
However, if you use the assignment operator for a reference value, it will not copy the value. Instead, both variables will reference the same object in the memory:
3041
+
3042
+
JS objects (as non-primitive data types) differ because they have reference values and those values are mutable. This means they share a memory address when shallow copied.
0 commit comments