Really confused - Basic Algorithm Scripting - Slice and Splice Challenge

Why doesn’t the following work? I saved arr2 to a new variable, but I’m getting the error: “The second array should remain the same after the function runs.” Why is this changing the second array?

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2;
  newArr.splice(n, 0, ...arr1);
  return newArr;
}

I looked at the hint and changed it to the below (adding the slice() method), and this worked. But I still don’t understand why otherwise arr2 ends up mutated when I am only altering the new variable I created.

function frankenSplice(arr1, arr2, n) {
let newArr = arr2.slice();
newArr.splice(n, 0, ...arr1);
return newArr;
}

Any insight is much appreciated because this is really bugging me!

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36

Challenge: Slice and Splice

Link to the challenge:

This doesn’t make a copy of the array. This makes a second variable that points to the same array.

1 Like

Thank you! I guess I knew that but it wasn’t registering for me that performing an operation on the variable would change the thing it points to.

I feel like understanding the difference could really save me some headaches in the future. :joy:

Yeah, it’s a common thing to trip people up. Objects act the same way.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.