But this doesn’t work. It just returns an empty array.
I read that .slice actually returns a ‘shallow copy’ which, by my understanding, returns the references to the original.
But this doesn’t really shed any light on the situation for me.
I also noticed that using let localArr = arr2; instead of let localArr = arr2.slice(); also works. So now we have two arrays that are the exact same, but one can’t be used
I realised now that .slice may not have anything to do with the reason? It looks like I have to use a local variable for .splice instead of the one I was passed
Array.prototype.splice mutates the array and returns removed items from the array. Since you are not removing any items but inserting elements, it returns an empty array.
You could do something like below but it doesn’t answer the question because the input arrays should not be mutated. The Array.prototype.slice creates a copy of the array before mutating it leaving the original arrays unchanged.
start is the index where you start inserting items, deleteCount is the number of items you want to delete starting from index start. item1, item2, …, itemN are the items you want to insert starting from index start. It returns an array containing the deleted items.
In your case the number of items to delete in the array is 0. Therefore, splice will return an empty array and your function will return the empty array returned by splice because of:
return arr2.splice(n, 0, ...arr1)
Yes. You can mutate arr2 on a separate line before returning it. However, you are not supposed to mutate any of the arrays passed. That is why you need to create a copy of the array using .slice or the spread syntax.
You can read more about .splice from the documentation.
Thanks for the explanation, it makes it much clearer!
Yeah, I had completed the challenge but was trying to play a round with it to better understand how it works. Took a bit of explaining for this to click