In JavaScript when multiple values of are grouped together, they are known as composite data types. Both arrays and objects are composite datatypes.

When you assign one of these composite datatypes to a variable, only the reference is saved and not the contents of the variable.

As a consequence, any change made to the values/contents using either of the variables gets referenced by both.

In other words, the assignment operator ‘=’ doesn’t create a new copy. It creates a new reference to the same data.

In order to copy one composite variable to another, iterate through each member of the composite variable and assign it to the target variable.

let a = [1,2,3];

let b=[];

let c=[];

b=a;/*This assigns by reference*/

/*The following copies by value*/

for (let i =0;i<a.length;i++){

c[i] = a[i];}

console.log(c);

--

--