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); // "[]"