Slice and Splice: "The second array should remain the same after the function runs."

Slice and Splice: "The second array should remain the same after the function runs."
0

#1

Tell us what’s happening:
I’ve got my code right so far, but I do not understand the last test:
“The second array should remain the same after the function runs.”
First I’ve copied arr2 into a new array by using the statement let newarr = arr2; within the function, but that won’t pass the last test. If I change it into the code shown below (spoiler) the answer is correct. Could someone explain me why?

Your code so far


function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let newarr = [...arr2];
  newarr.splice(n, 0, ...arr1);
  return newarr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice


#2

This statement does not copy the values in the array, but rather the reference to the array object. For example:

let a = [1, 2, 3];
let b = a;
let c = [1, 2, 3];
console.log(a===b); // true
console.log(a===c); // false
a.push(4);
console.log(b); // [1, 2, 3, 4]

How come the a and c arrays are not equal, even if they are arrays with the same elements? It’s because they are different objects, where changing one has no impact on the other. However, in the case of a and b, the let b = a line means that b contains a reference to the same object as a, which means that any change to a results in a change of b (imagine that a and b are two computers accessing the same Google document. If a changes something in the document, b will reflect this change, too.) In your case, let newarr = arr2; followed by a line where you change newarr (using splice), means that arr2 is also altered.


#3

Thanks for the well explained example! Now it makes sense.


#4

An easy way of cloning an array passed as a param might be

let arr2 = [...arr1];

This spreads the elements of arr1, but by wrapping that in the array brackets, they are immediately converted BACK into an array and assigned into arr2.