What's the meaning of "arr2.slice()"?

Anybody can tell me the reason that put a line of “let localArray = arr2.slice();” there?
I can’t understand the meaning of arr2.slice() as within the “()” is empty, thanks!

Question:

Slice and Splice

You are given two arrays and an index.

Copy each element of the first array into the second array, in order.

Begin inserting elements at index n of the second array.

Return the resulting array. The input arrays should remain the same after the function runs.

  **Your code so far**

function frankenSplice(arr1, arr2, n) {
let localArray = arr2.slice();
for (let i = 0; i < arr1.length; i++) {
  localArray.splice(n, 0, arr1[i]);
  n++;
}
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_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36

Challenge: Slice and Splice

Link to the challenge:

I believe slice() with no arguments just provides you with a shallow copy of the calling array. So localArray will be set to the same values as arr2 but it is a different array (so changes to localArray will not modify arr2).

1 Like

So how about just let localArray = arr2, why it needs a .slice()?


I got the answer now, thanks a lot!