Slice and Splice - Arr value changing

I declare: let newArray = arr2;

then I make changes to newArray: newArray.splice(n, 0, ...arr1);

But arr2 ends up changing. Why?

Your code so far

function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!

  let newArray = arr2;

  console.log("before", arr2);

  newArray.splice(n, 0, ...arr1);

  console.log("after", arr2);

  console.log(arr1, arr2, newArray);
  return newArray;

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/67.0.3396.87 Safari/537.36.

Link to the challenge:

When we assign an array or object (technically arrays are objects, but don’t let that confuse you) what is actually being assigned to the variable is what is called the “reference”. This is the place in memory where that object is stored. This means that when you do something like let newArray = arr2; your newArray isn’t actually a brand new copy of arr2. It has a copy of the reference which means that they are pointing to the same object in memory.

1 Like

So, like a pointer in C++?

Sorta. You can’t do weird pointer magic with it, but in terms of being a reference instead of a primative, yes.