Scenario 1:
var myArray = [2, 3, 4, 5];
function doStuff(arr) {
arr = [];
}
doStuff(myArray);
console.log(myArray); // [2,3,4,5]
>
In the first example:
You are altering the variable arr
which is merely just holding a reference to the array [2, 3, 4, 5]
, so instead of holding a reference to [2, 3, 4, 5]
, it will hold a reference to another array []
.
At the line var myArray = [2, 3, 4, 5];
:
myArray -----------------------------------> [2, 3, 4, 5]
Then at the line doStuff(myArray);
:
myArray -----------------------------------> [2, 3, 4, 5]
↑
arr ----------------------------------------------/
Then at the line arr = [];
:
myArray -----------------------------------> [2, 3, 4, 5]
arr ---------------------------------------> []
=> So, after the call to doStuff
, myArray
is still [2, 3, 4, 5]
.
In the second example:
You are using the reference to [2, 3, 4, 5]
stored in arr
to call a function pop
on it that alters it.
At the line var myArray = [2, 3, 4, 5];
:
myArray -----------------------------------> [2, 3, 4, 5]
Then at the line doStuff(myArray);
:
myArray -----------------------------------> [2, 3, 4, 5]
↑
arr ----------------------------------------------/
Then at the line arr.pop();
:
myArray -----------------------------------> [2, 3, 4, 5].pop()
↑
arr.pop() ----------------------------------------/
Which alters the array to:
myArray -----------------------------------> [2, 3, 4]
↑
arr ----------------------------------------------/
=> So, after the call to doStuff
, myArray
is now [2, 3, 4]
.