roadtocode
roadtocode

Reputation: 339

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];
    }
}

Upvotes: 3

Views: 76

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

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.

Upvotes: 3

Related Questions