The reason for this in your code is because you are simply telling your test
function to point to the globalarray
with the =
operator. This is because in JavaScript, variable assignments do not inherently "copy" objects into the new variables; this might seem confusing, so just think of the =
operator as a sign that points your code to the location of an object.
The only times that the =
operator is making new copies is when you are working with primitive types. In those cases, you cannot inherently change what those objects are, so =
is sufficient to make a copy like you would expect.
The reason for the .slice().reverse()
is to work around the problem you are seeing. Another way you could do this is by using let localarray = globalarray.map(e => e)
, or as samee suggested, by using let localarray = [...globalarray]
. The .map
operator takes the function given to it as the first argument and applies it to every element, and then it stores the result in a different array at another location that is not the same as globalarray
.
Keep in mind that these methods, and any others that might be suggested to you, are shorthand ways of doing
let localarray = new Array(globalarray.length);
for (let i = 0; i < globalarray.length; i++) {
localarray[i] = globalarray[i];
}
// localarray can now be freely modified because it does not point to the same array as globalarray
Also keep in mind that if you need to also create copies of the elements inside of the arrays, then you will have to use more comprehensive copying code. There are libraries that can do this sort of heavy-duty copying if you really need it.