Implement the Slice and Splice Algorithm

JavaScript Code:

function frankenSplice(array1, array2, index) {
  let shadowCopyOfArray1 = array1.slice();
  let shadowCopyOfArray2 = array2.slice();
  console.log(array2.slice());// [4, 5]
  console.log(shadowCopyOfArray2)//[ 4, 1, 2, 3, 5 ]
  for (let i = 0; i < shadowCopyOfArray1.length; i++) {
    shadowCopyOfArray2.splice(index, 0, shadowCopyOfArray1[i]);
    index++;
  }
  return shadowCopyOfArray2;
}

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

Question:

Why the result of outputing shadowCopyOfArray2 variable to console before modifying it is the result after modifying it?
It does not make any sense…
Can anybody find the problem?

  • perhaps it was done (tentatively) to see before and after results for troubleshooting or to be sure, if you want you can add another console log to see after results

happy coding :slight_smile:

Could you link to the challenge?

this is one of those weird things that are just like that: shadowCopyOfArray2 is a mutable object, the console.log can show any of its states

in the browser console you can appreciate the weirdness more:

the preview has 2 elements, but when you expand to see more details, it has the elements that it has at the end

You should do something like
console.log(JSON.stringify(shadowCopyOfArray2)) to not have it change while logged

1 Like

Does it happen only when I create the shadowcopy of one array and then assgin the copy to a variable?

console.log method will choose to output the last state of an object?

it’s not a choice, it is how it is

it happens everytime you print a mutable object that is mutated later