Failing last test on Slice and Splice

Failing last test on Slice and Splice
0

#1

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…?


#2

splice()modifies the array it is called on.


#3

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.


#4

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!