0

I'm trying to create a function proposed by freeCodeCamp that operates as follows:

"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."

Solution being

function f(arr1, arr2, n) {
  let dummy_arr2 = arr2.slice();
  a2.splice(n, 0, ...arr1);
  return dummy_arr2;
};

Now, when I simply use dummy_arr2 = arr2 on the second line, without the slice() operator, arr2 doesn't remain unchanged. Why is this?

Rifky Niyas
  • 1,737
  • 10
  • 25
  • `.slice()` returns a _copy_ of the original array whereas `arr2 = arr1` will make `arr2` point to the _same_ array which `arr1` points to. – Yousaf Aug 19 '21 at 12:14
  • The wording of that question leaves a lot to be desired. If the arrays should "remain the same" then "copy ... into" is clearly misleading. – Pointy Aug 19 '21 at 12:14

0 Answers0