In your first example you didn't create a new array - you created a new reference to an already existing array (so you had 2 references but 1 array). When you modify the array through one reference, you'll see changes through the other reference as well (since you really only have 1 array).
To create an independent copy of an array, you need to actually create a new array instance and then copy the items over. This can be done through a shallow or through a deep copy.
In short, a shallow copy can be created using the Array.concat()
or the Array.slice()
methods (or using a loop, like in your 2nd example). For a deep copy, you'll have to also copy the objects inside the array - this would likely need more code, depending on what kind of objects are in the array.
When your array only contains primitive (or pimitive-like) types, a shallow copy is typically enough - if your array only has strings, a shallow copy should be enough since String
behaves like a primitve type even though it's a complex object.
Read this article for more information.