Sethen
Sethen

Reputation: 11348

Strange behavior with Arrays and slice

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?

Upvotes: 4

Views: 95

Answers (2)

lontivero
lontivero

Reputation: 5275

Because arrays are references then, slice copy the references and not the values.

Upvotes: 0

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

It's a distinction between shallow copying and deep copying.

slice result 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.

Upvotes: 6

Related Questions