Unintentionally editing arr2

Tell us what’s happening:

My output from my code below is:
[ 4, 5, 6 ] [ 4, 1, 2, 3, 5, 6 ]

What I expect to appear in the console is:
[ 4, 5, 6 ] [ 4, 5, 6 ]

Why is this happening? I am trying to edit arr3, not arr2, but arr2 is clearly changing. Thanks for the help in advance.

Your code so far


function frankenSplice(arr1, arr2, n) {

let arr3 = arr2;
console.log(arr2);
arr3.splice(n,0, ...arr1);  //arr2 is changing here somehow
console.log(arr2);

return arr3;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 12739.111.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36.

Challenge: Slice and Splice

Link to the challenge:

Use this instead:

let arr3 = [...arr2];

What’s going on?

By doing this:
let arr3 = arr2;

you are passing the reference from arr2 to arr3, therefore it can be said that they are the same. What you do in arr2 will be reflected in arr3 and vice versa.

To avoid this behavior to arr3 you must pass the copy of the elements in arr2, this is achieved in two ways:

1- let arr3 = [... arr2]
or
2- let arr3 = arr2.slice(0)

As you are in the ‘Slice and Splice’ challenges, I recommend the second method

Sorry for the bad English.

You are making a shallow copy of arr2. arr2 and arr3 point at the same memory. You want to make a deep copy so arr3 is a new array with the same contents. There are lots of ways to do that, but a spread operator, in the post above, is the usual way.

Thank you both of you! I did not know about the diference between deep vs shallow copies, both of your explanations made sense.

And @gtaypeg your english is just fine! :grin:

2 Likes