3

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];
    }
}
3
  • Well if you pass the same array into both parameters, nothing gets created here at all. Commented Aug 29, 2015 at 15:11
  • 1
    What is your understanding of "deep" and "shallow copy"? Commented Aug 29, 2015 at 15:11
  • technically, you aren't allocating any new memory here at all, since these arrays are allocated somewhere else and passed in as parameters. This would likely be a "mixed" array, depending on if the elements are primitives or objects. Commented Aug 29, 2015 at 15:19

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Amazing. Thanks a lot man :) One question though, When you say they are copied as reference, how is the address of the memory in which the object is stored in passed inside the array?
"as an object reference" is as far as I can explain it :-) It's how any object assignment, ever, works in Javascript. It's opaque - you can't examine the address or do any operations other than assignment or referencing the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.