COPY BY VALUE A COMPOSITE DATA TYPE
primitive data types are passed in by value
composite data types i.e.., non-primitive data types are passed in by reference
let’s see the basic program of copy by value
let a =2;
Imagine,these variables of data used to store our values declaring a variable a and similarly the value of a is stored in b.We can allocate another variable c and now we have also changed the value of c only the original value is copied and it does not disturb the value of c hence, we pass the primitive value directly. value do not affect the original value.
Similarly, let’s see the basic program of copy by reference
How do we copy by value in a composite data type ?
The most intermediate way to approach copy by value by using spread operator.
let arr = [1,2,3];
let arr2 = […arr];
console.log(arr); // [ 1,2,3 ]
arr2.push(‘d’); //inserting an element at the end of arr2
console.log(arr2); // [ 1,2,3,4 ]
Here, arr 2 has the elements of arr1 copied into it if any changes are made it would reflect the other, In this way the spread operator is used .