Failing last test on Slice and Splice

Failing last test on Slice and Splice


function frankenSplice(arr1, arr2, n) {

let newArr = arr2;
for (var i = 0; i < arr1.length; i++) {
newArr.splice(n+i, 0, arr1[i]);

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

I’m getting the right output but my arr2 is being altered and I’m not understanding why. I thought by creating the var newArr I would no longer be altering arr2…?


splice()modifies the array it is called on.


Your code actually makes two variables pointing to the same array - major point of confusion that is common to many programming languages. Javascript assigns objects (which includes arrays) by reference.

Since your array is only one level deep you could make a shallow copy or you could find a way to create newArr so that your parameter array is not altered.


You know I got confused, when I searched for slice on MDN I found string.prototye.slice() and didn’t realize it could be called on an array also! This allowed me to create a copy in my var and pass the last test. Thanks!