The way JavaScript memory storage works is with a stack of Execution Contexts. Each one of these Execution Contexts has a Lexical Environment, and a Variable Environment.
The Lexical Environment is the set of variables that came from all the parent Execution Contexts, for example, the variables saved in the global context will always be available for this reason.
The Variable Environment is the set of variables that are being declared in the current Execution Context. This is what you are changing in your example, the Variable Environment variable.
function change(array) {
var array2 = ["222"];
array = array2;
}
In this example, array
is saved in the Variable Environment. Then, array2
is also saved in the Variable Environment. As you can see, the Lexical Environment is not changed here at all. So once execution completes in the function, and control returns, this Execution Context loses scope and is eligible for garbage collection since it has no ties to any Lexical Environments.
That is why the process you used did not replace the array you passed in. You merely replaced a value in the local scope.
You can still modify the array passed in and it will change the array itself, but if you assign to that variable then it will no longer be changing the array.