So I tried doing this challenge without mutating arr2.
My solution was to save arr2 into a new variable, and mutate the new variable instead, leaving arr2 unaltered, like thus-
let localArray = arr2;
after this, I only ever do anything to the values in localArray, and don’t do anything with the values of arr2, however, when I do a console.log test later in the function I see that arr2 HAS been mutated. Why?
I know that the solution is to use slice() function, ie replace this line-
let localArray = arr2;
with this line -
let localArray = arr2.slice();
but I am not sure why that works. Can someone please explain it?
Your code so far
function frankenSplice(arr1, arr2, n) {
let localArray = arr2;
console.log(localArray);
localArray.splice(n, 0, ...arr1);
console.log(arr2)
return localArray;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36
.
Challenge: Slice and Splice
Link to the challenge: