# Array by Reference vs Array by Value in Javascript

I'm reading Data Structures and Algorithms with Javascript by O'reily and it states the following:

Shallow copy (two arrays point to the same location in memory):

``var nums = [];for (var i = 0; i < 100; ++i) {nums[i] = i+1;}var samenums = nums;nums[0] = 400;print(samenums[0]); // displays 400``

Deep copy:

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

Now the following code fragment produces the expected result:

``var nums = [];for (var i = 0; i < 100; ++i) {nums[i] = i+1;}var samenums = [];copy(nums, samenums);nums[0] = 400;print(samenums[0]); // displays 1``

Why is a function required in order to create deep copies?

As stated in the comments, the function is purely for aesthetics and reusability, and is not strictly necessary.

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

var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
nums[0] = 400;
``````

into this equivalent function-less example:

``````var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}