Why does this mutate arr2?

Can someone please assist in explaining why arr2 gets mutated in my code below, I feel this is an important thing for me to know to properly understand arrays.

My solution yields the right answer but arr2 is mutated in the process and I don’t understand why as I am doing the work on myArray?

function frankenSplice(arr1, arr2, n) {
const myArray = arr2
myArray.splice(n, 0, ...arr1)
return myArray;

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

Challenge: Slice and Splice

Link to the challenge:

The Array.prototype.splice() method is being used. This method is said to be a destructive array method, because it changes the original array.

1 Like

Thanks for your reply, however, the method is being applied to myArray. Why does it have an impact on arr2? That is what I am struggling to understand.

Hyy @CassiuSRSA,

It’s mutating arr2 because in programming arrays can be referenced and not copied. In simple words, when you share a web page you simply copy it’s url and not full webpage with whole of HTML and CSS. And when it’s author make changes to it, the changes can be seen in it’s link and also on everyone’s screens, right? That’s same with arrays you can’t copy the content but when you can assign it to a newer variable, behind the scenes computer assigns url (reference) to the previous or originals list.

Hope you got you answer.
Have a great day ahead! :rose:


Thanks imGarvish.

So simply making arr1 = arr2 does not mean arr1 is an independent array then? Whatever you change to arr1 will impact on arr2 and vice versa?

But then if you go arr1 = arr2.slice() this then creates a whole new array?

Just checking if I am understanding it correctly. Sorry some things I am learning quick and somethings are giving me sleepless night, don’t get me started on prototypes :open_mouth:

1 Like

Yes, yes!

Yes because its copying the elements from within arr2 and not referencing the array itself. You can also copy using;

let newArr = [...arr2];

It’s okay, coding is actually hard for some people and you can ace in it with practice! Happy Coding! :keyboard:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.