Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this javascript function create a deep copy instead of a shallow copy?

This is the code and according to a book I'm reading, it states that arr2 can be a deep copy, meaning new memory is allocated to store the object, which in this case is arr2.

function copy(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        arr2[i] = arr1[i];
    }
}
like image 727
roadtocode Avatar asked Mar 24 '26 03:03

roadtocode


1 Answers

It's not a deep copy. Yes, new memory is allocated for the array itself and its elements, but if objects are part of the array, they are copied as references. New objects are not created.

If it were a deep copy, changing an object stored in arr1 wouldn't change the corresponding object copied into arr2, but it does:

function copy(arr1, arr2) {
  for (var i = 0; i < arr1.length; ++i) {
    arr2[i] = arr1[i];
  }
}

var arr1 = [1, 2, { 'foo': 'bar' }];
var arr2 = [];

copy(arr1, arr2);

console.dir(arr1);
console.dir(arr2);

arr1[2].foo = 'changed';

console.dir(arr1);    // changed, of course
console.dir(arr2);    // also changed. shallow copy.
like image 112
Paul Roub Avatar answered Mar 26 '26 16:03

Paul Roub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!