Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to the array passed to a function

var arrN = [1, 2, 3];

function init(arr){
   arr = [];
   console.log(arrN) //output [1, 2, 3], expect []  
}

init(arrN);

When using splice or push methods the array passed to a function is being modified. So I am trying to understand what is happening when using assignment operator, why it's not changing the array? is it creating the local var of the passed array?

Any help will be appreciated!

like image 743
andrey Avatar asked Feb 26 '17 15:02

andrey


2 Answers

You need to distinguish between the variable and the actual object (the array). splice and push are changing the object. arr = [] is just changing the variable, the old object just stays as it is.

like image 58
Meier Avatar answered Oct 13 '22 21:10

Meier


There is a difference in assigning a different object to a variable or mutating the object currently referenced by a variable.

(Re)assigning

When you do an assignment like:

arr = []; // or any other value

... then the value that arr previously had is not altered. It is just that arr detaches from that previous value and references a new value instead. The original value (if it is an object) lives on, but arr no longer has access to it.

Side note: if no other variable references the previous value any more, the garbage collector will at some point in time free the memory used by it. But this is not your case, since the global variable arrN still references the original value.

Mutating

It is another thing if you don't assign a value to arr, but apply instead a mutation to it, for instance with splice, push, pop, or an assignment to one of its properties, like arr[0] = 1 or arr[1]++. In those cases, arr keeps referencing the same object, and the changes are made to the object it references, which is visible to any other variable that references the same object, like arrN.

Clearing an array

Now if you want to clear the array that is passed to your function, you must avoid to make an assignment like arr = .... Instead, use methods that mutate the array in place:

arr.splice(0)

Or, alternatively:

arr.length = 0;

Now you have actually mutated the array, which is also the array referenced by arrN.

like image 30
trincot Avatar answered Oct 13 '22 22:10

trincot