There is a difference in assigning another object to a variable or mutating an object that is currently referencing a variable.
(Re) appointment
When you complete a task, for example:
arr = []; // or any other value
... then the value that arr
previously had was not changed . Just arr
separated from the previous value and instead refers to the new value. The original value (if it is an object) lives on, but arr
no longer has access to it.
Side note: if no other variable refers to the previous value anymore, the garbage collector will free up the memory it uses at some point in time. But this is not your case, since the global variable arrN
still refers to the original value.
Mutating
Another thing is if you do not assign the value of arr
, but instead apply a mutation to it, for example, with splice
, push
, pop
or assigning one of its properties, such as arr[0] = 1
or arr[1]++
. In these cases, arr
continues to refer to the same object, and changes are made to the object that it refers to, which is visible for any other variable that refers to the same object, for example arrN
.
Array cleaning
Now, if you want to clear the array that is passed to your function, you should avoid doing a job 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
.
source share