Javascript passing arrays to functions by value, leaving original array unaltered

Inside your function there’s this:

funcArray = new Array();
funcArray = someArray;

This won’t actually copy someArray but instead reference it, which is why the original array is modified.

You can use Array.slice() to create a so-called shallow copy of the array.

var funcArray = someArray.slice(0);

The original array will be unaltered, but each of its elements would still reference their corresponding entries in the original array. For “deep cloning” you need to do this recursively; the most efficient way is discussed in the following question:

What is the most efficient way to deep clone an object in JavaScript?

Btw, I’ve added var before funcArray. Doing so makes it local to the function instead of being a global variable.

Leave a Comment