How to do copy by value of a composite data type in JavaScript?

Santosh Kumar Divate
2 min readNov 5, 2020

--

Composite data types are a combination of primitives and other data types. They include arrays, objects. In JavaScript composite data types are “copied by reference” by default.

For example:

let arr1=[10,20];
let arr2=arr;
arr1.push(100);
console.log(arr1);//[10,20,100]
console.log(arr2);//[10,20,100]

From the above example you can see that the “push()” operation on the second array(arr2) will be reflected in the first array(arr1) as both the array variables(arr1, arr2) are pointing to the same memory space. So modifying anything in one array will get reflected in the other array. This is due to “copy by reference” nature of composite composite datatypes.

There are 3 ways by which we can do a “copy by value” of composite data types. They are:

  1. Using the spread () syntax
  2. Using the JSON.stringify() and JSON.parse() methods
  3. Using the Object.assign() method

The following examples shows the use of above 3 methods:

  1. Using spread ():
let array1=[10,20,30];
let mail1={from:'Cisco',msg:'Run'};

let array2=[...array1];
let mail2={...mail1};
array2.push(40);
mail2['to']='Barry Allen';
console.log(array1);//[ 10, 20, 30 ]
console.log(array2);//[ 10, 20, 30, 40 ]
console.log(mail1);//{ from: 'Cisco', msg: 'Run' }
console.log(mail2);//{ from: 'Cisco', msg: 'Run', to: 'flash' }

2. Using JSON.stringify() and JSON.parse() methods:

let array1=[10,20,30];
let mail1={from:'Cisco',msg:'Run'};

let array2=JSON.parse(JSON.stringify(array1));
let mail2=JSON.parse(JSON.stringify(mail1));
array2.push(40);
mail2['to']='Barry Allen';
console.log(array1);//[ 10, 20, 30 ]
console.log(array2);//[ 10, 20, 30, 40 ]
console.log(mail1);//{ from: 'Cisco', msg: 'Run' }
console.log(mail2);//{ from: 'Cisco', msg: 'Run', to: 'flash' }

3. Using the Object.assign() method:

let array1=[10,20,30];
let mail1={from:'Cisco',msg:'Run'};
let array2=Object.assign([],array1);
let mail2=Object.assign({},mail1);
array2.push(40);
mail2['to']='Barry Allen';
console.log(array1);//[ 10, 20, 30 ]
console.log(array2);//[ 10, 20, 30, 40 ]
console.log(mail1);//{ from: 'Cisco', msg: 'Run' }
console.log(mail2);//{ from: 'Cisco', msg: 'Run', to: 'flash' }

Here spread () and Object.assign() does a “shallow copy”(internal objects are “copied by reference”) where as JSON.stringify() and JSON.parse() methods do a “deep copy”(internal objects are “copied by value”).

--

--

No responses yet