Can someone please explain this to me?

Here is my code for the challenge.

function frankenSplice(arr1, arr2, n) {
let newArr2 = arr2.slice(0);
let tailArr2 = newArr2.slice(n);
newArr2.splice(n,newArr2.length-1);
for (let i = 0; i<arr1.length; i++){
  newArr2.push(arr1[i]);
}
for (let j = 0; j<tailArr2.length; j++){
  newArr2.push(tailArr2[j]);
}
return newArr2;
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

and it’s works! However, before I solved this, I ran into a problem that at line 2, my first code was like this:

let newArr2 = arr2;

and then I start to modify the value of array newArr2. But by modifying the value of newArr2 cause the value of arr2 to change too! Can someone please explain how does that happen? :frowning:

Challenge: Slice and Splice

Link to the challenge:

That’s because let newArr2 = arr2; doesn’t create new array, but just assigns another name to the array that arr2 is already pointing to. After that both newArr2 and arr2 refers to the same array. This makes it look like changing one changes both, but in fact there’s only one object changed, only it can be accessed using two variables.

arr2.slice(0) returns new array. As a side note, if the items in array would be also arrays, then those nested arrays would display similar behavior with their corresponding counterparts as in the case above.

1 Like