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.


Make a copy of the array that you can use.

A simple way to do this is by using var clone = original.slice(0);


A variable pointing to an array is a reference to it. When you pass an array, you're copying this reference.

You can make a shallow copy with slice(). If you want a full depth copy, then recurse in sub objects, keeping in mind the caveats when copying some objects.