To understand why this is happening you must first remember that an Array in Javascript is an object . The reason your arr = []
is taking no affect on your global declaration is for the following :
Reason 1 :
arr = []
does not clear an array , it just creates a new array object in memory no matter what .
So in your function :
function doStuff(arr) {
arr = [];
};
doStuff(myArray)
you are just taking in myArray and making a new empty version of it in a local scope which leads to reason 2 .
Reason 2 :
Any new object / variable declared in a function is confined to the local scope of that function
so :
function doStuff(arr) {
arr = [];
};
doStuff(myArray) //logs [1,2,3,4]
arr = []
was destroyed at the closing bracket of doStuff function an cannot exist on the outside .
Reason 3 :
function doStuff(arr){
arr[2] = 25;
}
doStuff(myArray)
This works because you're accessing myArray in arr variable and modifying a property off myArray object, this is perfectly normal in javascript.
In short :
=
operator assigns , re-assigns , and creates ...
arr = []
is an assignment to new myArray object within your function and is also trapped in the scope of your function .
arr[2] = 25
accesses myArray object temporarily and re-assigns a property .
Hope this helps..