Slice and Splice questions

Why cant you do this code:

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

Like this

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

Thanks,
Andrej

because splice returns an array with the removed elements (in this case returns an empty array), not the array on which it is used

This explanation doesn’t make sense to me.
Why does it

it returns an empty array because you have removed 0 elements (second argument of splice is 0)

the returned value of splice is the array with the removed elements, you can find it in the documentation about the splice method

This explanation doesn’t make sense to me.
Why does it:

because splice returns the array with removed elements, as this time the elements removed are 0, it returns an array with 0 elements, so it is empty

.slice() makes a copy of an array.
.splice() mutates the array.

Ex:

let evens = [2, 4, 6, 8];

// beginning with 0th index remove 1 element.
evens.splice(0, 1); 
console.log(evens); // [4, 6, 8]

Had you set it to a variable…

let odds = [1, 3, 5, 7, 9];
const removed_elements = odds.splice(0, 1);

console.log(odds); // [3, 5, 7, 9]
console.log(removed_elements); // [1]

In my experience,. most senior developers stay away from mutating. It’s generally better to use a copy and modify the copy instead. It’s far easier to debug.

1 Like