0

I'm puzzled as to why the following two versions of test function produces different results:

var arr = [1, 2, 3, 4, 5];

var test1 = function(array) {
  array = [];
  array[0] = 5;
}

var test2 = function(array) {
  array[0] = 5;
}

test1(arr);
console.log(arr);
test2(arr);
console.log(arr);

test1 fails to change the content of arr, while test2 works. Apparently this is the effect of array=[]. But I'm not sure why it is the case!

Rayon
  • 36,219
  • 4
  • 49
  • 76
NatashaC
  • 512
  • 1
  • 10
  • 22

2 Answers2

2

In test2() you are modifying the array you passed in, so you are seeing expected behavior.

In test1() you are assigning a brand new array to the function's array argument variable (overriding the reference to arr), then you are modifying that new array.

More info...

It will help to understand what it means to "pass by reference".

When you pass an array into a function, you're passing a "reference" to the array. So you can modify that array (via that reference) and you'll be able to see the changes outside of the function. However, what you're doing in test1() is overwriting your reference with a reference to a new array, and because you're not returning that new reference from the function you will not be able to see the new array outside of the function.

Here's an example where you can assign that new array back to arr:

var arr=[1,2,3,4,5];
function test3(array) {
  array = [];     // "array" is now a new, empty array
  return array;   // return the new array
}
arr = test3(arr); // assign the result of test3 back to arr
console.log(arr); // "[]"
chardy
  • 1,233
  • 1
  • 10
  • 18
0

test1 function creates a new new array when you do array=[] and it is updating the new Array. But the test2 is updating the array it receive as parameter

Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38