COPY BY VALUE A COMPOSITE DATA TYPE

Jagan mohan
Nov 3, 2020

String,Number,Boolean are primitive data types whereas Objects and Arrays are composite data types in JavaScript.

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;

let b=a;

console.log(b,a)//2,2

console.log(b,a)//2,4

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

let copybyref={

a :2

}

let b={…3};

console.log(copybyref.a)//2

copybyref.a=5;

console.log(copybyref.a)//5

In this example, When we create a variable javascript stores it’s location. when we copy the variable we copy the location of our original value is copied i.e.., copybyref.a is referencing the location of a.If we change any value of it,and it will also change the original value.

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 ]

console.log(arr);

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 .

--

--

Jagan mohan

Strings,Booleans can be classified as primitive data types whereas Arrays and Objects are composite data types