I was playing around with some arrays in JavaScript when I came across something strange. Here is my code:
var origArray = new Array("one","two","three","four","five","six","seven","eight");
var newArray = origArray.slice(1,3);
origArray[1] = "octopus";
console.log(newArray.join()); //prints two,three
var origArray = new Array(["one","two"],["three","four"],["five","six"],["seven","eight"]);
var newArray = origArray.slice(1,3);
origArray[1][0] = "octopus";
console.log(newArray.join()); //prints octopus,four,five,six
I don’t understand why newArray gets affected in the second case and not the first. What’s going on here?
It’s a distinction between shallow copying and deep copying.
sliceresult is another object than the original, but it does not mean that objects within array (all the way down) were duplicated. If those inner objects happen to be arrays, they are shared between the copy and the original.