Slice and Splice -- recreated arr2

Tell us what’s happening:
this solution does not pass the test, because “The second array should remain the same after the function runs.”
But it is the same. Or it is not?

Your code so far

function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let end = [];
  let result = [];
  end = arr2.splice(n);
  result = arr2.concat(arr1.concat(end));
  arr2 = arr2.concat(end);
  return result;

frankenSplice([1, 2, 3], [4, 5, 6], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.

Link to the challenge:

As soon as you spliced arr2, you mutated it. You reassigned a value back to arr2, but you created a new reference which is not the same as the original. It may have the same values, but it is not the same array.

if you look up the splice specification you will see it says that:

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
here’s my ref:

so given that arr2.splice is changing your arr2, and the challenge gave you an error that says “The second array should remain the same…”, I think this gives you all you need to figure out what is wrong and move forward.

1 Like

OK, I will change it. Thanks.

why this statement would modify arr2:
end = arr2;
and this would not:
end = arr2.slice();


end = arr2;

just assigns a reference to same array that arr2 reference

end = arr2.slice();

assigns a reference to a new array that is a shallow copy of the array referenced by arr2.

Compound values such as arrays and objects are assigned by reference where as scalar primitive values (like Number, String, Boolean, undefined, null, Symbol) are assigned by-value. The references of arrays and objects “point” to the values stored in variables.

1 Like

thank very much for your help.