Why is arr2 changing?

Tell us what’s happening:
I am trying to splice a copy(newArr) of arr2 without changing arr2. Why is arr2 changing? Am I missing someing simple?

Thanks for your help.

  **Your code so far**

function frankenSplice(arr1, arr2, n) {
let newArr = arr2;
newArr.splice(n, 0, ...arr1);
return newArr;


frankenSplice([1, 2, 3], [4, 5, 6], 1);
  **Your browser information:**

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

Challenge: Slice and Splice

Link to the challenge:

This doesn’t copy the array.

that assigns one array to another (i believe they refer to it as being ‘by reference’?), which is not the same as a copy.
you could use newArray=array.map((x)=>x)
that copies each individual value to create a new array

so are you saying that what I am doing with newArr is basically creating a reference to arr2, and if newArr changes so does arr2? Thanks for the reply by the way.

p.s. solved it by using newArr = […arr2]


thank you for your response

yes, i believe thats the case.
get’s a bit complicated, partly by dealing with deeper/multi dimensional arrays.
some bedtime reading:

1 Like

You’ve got it right.
Primitive types (strings, numbers, booleans, ‘undefined’, ‘null’) are copied by value, but objects (everything else is a type of object) are copied by reference.

let num1 = 42;
let num2 = num1;
num1 = 69;
console.log(num1); // 69
console.log(num2); // 42

let arr1 = ['a', 'b', 'c'];
let arr2 = arr1; // there is one array in memory that both of these variables link to
console.log(arr1); // ['a', 'b', 'c', 'd', 'cheese']
console.log(arr2); // ['a', 'b', 'c', 'd', 'cheese']
1 Like

Thank you that makes things a lot more clear!

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