How do you copy by value a composite data type?

You can copy any object either by “Copy by value” or “Copy by reference”

Copy by reference : In copy by reference both actual variable and copied variable refer to the same memory address. So change in either of variables will reflect in the other.

Copy by value : Unlike copy by reference in copy by value, the object is copied in to a new memory location, so the actual variable and copied variable refer to different locations. So changes in one variable doesnt reflect in the other.

In Javascript there are three different data types.

  1. Primitive(String,Number,Boolean)
  2. Special(Undefined,Null)
  3. Composite(Object,Array,Function)

We can copy by value a composite data type using spread operator as follows

var a = [1,2,3];
var b= [...a];
b[3] = 4;
console.log(a);
console.log(b);

We can also use Object.assign method as follows

var a = [1,2,3];
var b= Object.assign([],a)
b[3] = 4;
console.log(a);
console.log(b);

--

--