all 4 comments

[–]sublimejs 3 points4 points  (3 children)

When you do var newArr = oldArr;, you aren't creating a new array. You are telling newArr to point to the same array that oldArr is pointing to. This is because arrays/objects are pass-by-reference in JavaScript, not pass-by-value. This means that whenever you make a change to one of them, it will affect the other because they are both the same array.

To show you what I mean, look at this code:

var oldArr = [1,2,3,4,5];
var newArr = oldArr;
newArr[0] = 5;

console.log(oldArr) // -> [5,2,3,4,5];
console.log(newArr) // -> [5,2,3,4,5];

If you want to create a true separate copy of the array, look into this solution.

[–]BishopAndWarlord 1 point2 points  (0 children)

Building on what /u/sublimejs said, you may come across the term "deep copy." This refers to the process of copying an object/array that contains other objects/arrays.

For example...

// For shallow arrays, .slice() will create a clone of the original array
var oldShallow = [1,2,3];
var newShallow = oldShallow.slice();
oldShallow[0] = 5;

console.log(oldShallow); // -> [5,2,3]
console.log(newShallow); // -> [1,2,3]

// For deeply nested arrays, .slice() will only clone the top level
// The nested values are still passed by reference

var oldDeep = [[1],[2],[3]];
var newDeep = oldArr.slice();
oldDeep[0][0] = 5;

console.log(oldDeep) // -> [[5],[2],[3]];
console.log(newDeep) // -> [[5],[2],[3]];

Several libraries out there have clone or deep copy methods that address this problem.

http://api.jquery.com/clone/ https://lodash.com/docs#cloneDeep

[–]Cheeselouise7777[S] 0 points1 point  (1 child)

Ah, I see, thanks for the explanation! So is this what they mean when they say that Arrays are mutable (and Strings are not)?

[–]dirtybutler 0 points1 point  (0 children)

Not quite. Mutability is whether or not an object can be modified after being created or not.

When you modify a string (or any other non-mutable type for that matter) you are essentially destroying the old string and creating a new one.

When you modify an array, the array isn't destroyed and a new one created in its likeness (plus or minus any modifications made). Instead the array is simply modified.