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