Why is the variable being mutated in this example?

So I tried doing this challenge without mutating arr2.

My solution was to save arr2 into a new variable, and mutate the new variable instead, leaving arr2 unaltered, like thus-

let localArray = arr2;

after this, I only ever do anything to the values in localArray, and don’t do anything with the values of arr2, however, when I do a console.log test later in the function I see that arr2 HAS been mutated. Why?

I know that the solution is to use slice() function, ie replace this line-

let localArray = arr2;

with this line -

let localArray = arr2.slice();

but I am not sure why that works. Can someone please explain it?

Your code so far


function frankenSplice(arr1, arr2, n) {
let localArray = arr2;
console.log(localArray);
localArray.splice(n, 0, ...arr1);
console.log(arr2)
return localArray;
}

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

Your browser information:

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

Challenge: Slice and Splice

Link to the challenge:

You have created a shallow copy, so you have two variables that point to the same memory. Try making a deep copy.

// Shallow
let arr2 = arr1;
// Deep
let arr3 = [...arr1]

You cannot assign Arrays and Objects like that because they are not primitive values. If you do this: let localArray = arr2 , both localArray and arr2 will reference the same array (point to the same array). Any mutation via one reference will be reflected in the other. If you want to create a new array, you can use the spread operator:
let localArray = [...arr2] or any other technique for cloning arrays or objects.
Check This Blog post and This in depth FCC article will shed more light on the topic.

Some more reading material.

YDKJS: value-vs-reference
JavaScript for impatient programmers: values