Slice Splice and everything nice

Tell us what’s happening:
Hi,

could someone tell me why with my solutions (one uses the …spread and it’s in comments) I get this message? I do make copies of the arrays (I think)
// running tests
The second array should remain the same after the function runs.
// tests completed
// console output

[ 4, 1, 2, 3, 5, 6 ]

Thank you
L

Your code so far


function frankenSplice(arr1, arr2, n) {

let elements = arr1.slice(0);
let totalArray = arr2;
for (let i = 0; i < arr1.length; i++){
  totalArray.splice(n+i, 0, elements[i])
};

 
 return totalArray ;
}

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

/*
function frankenSplice(arr1, arr2, n) {
 let totalArray = arr2;
 totalArray.splice(n, 0, ...arr1)
 return totalArray;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Slice and Splice

Link to the challenge:

you need to make a copy of the array on which you use splice, so arr2, instead you made a copy of arr1 without needing to

Hi,

I can see the redundancy of the .slice on arr1 now, thank you
So the let totalArray = arr2; operation does not create a new variable on which I can work without tampering the arr2? I have studied computer Science and I was taught that a variable is an isolated memory space, but this seems obsolete now. Must be related to the reference of a data

L

arrays work by reference
what you are doing with

is making a different reference to the same array, to make a copy you need to use a certain method

You could find interesting the Just Javascript course for a rapresentations of how variables work in Javascript

In javascript Arrays and Objects are pass-by-reference instead of pass-by-value. so when you enter:

let totalArray = arr2

You’re not simply assigning the value of arr2 to totalArray, you’re essentially assigning totalArray the memory location of arr2.

What you want instead is a fresh copy you can work with without altering the original. You can do this with the slice function.

thank you again for this!