Why is splice affecting arr2 argument?

Hey guys,

I am assigning the splice method to result but for some reason arr2 is still being affected.

function frankenSplice(arr1, arr2, n) {
    let result = arr2;
    for (let i = arr1.length - 1; i >= 0; i--) {
        result.splice(n, 0, arr1[i]);
    return result;
console.log(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2));

[ ‘head’, ‘shoulders’, ‘claw’, ‘tentacle’, ‘knees’, ‘toes’ ]
[ ‘head’, ‘shoulders’, ‘claw’, ‘tentacle’, ‘knees’, ‘toes’ ]

this is not making a copy, this is creating a new reference to the same array, so if you edit result, arr2 is also affected

remember ways to copy arrays!

1 Like

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