Spread operator - splice() and slice()

Hi there,
I have a couple of questions regarding the slice and splice exercise.
First question: I can’t understand why the use of the spread operator (…) would remove the brackets in the first array. My initial code , without the spread operator, would copy the items but would keep the [brackets]. Why is that? I see the use of the spread operator gives the expected answer. I’m just not sure why…

//initial code
copyOfArr2.splice(n,0, arr1); // the result here was [4, [1, 2, 3] 5, 6]

Second Question: I tried creating a variable that would hold the splice method for copyOfArr2, but when i tried returning that variable, it wouldn’t work. Why is that?

var newArr =copyOfArr2.splice(n,0, ...arr1);
  **Your code so far**

The code below was accepted.


function frankenSplice(arr1, arr2, n) {
var copyOfArr2 = arr2.slice();
copyOfArr2.splice(n,0, ...arr1);
console.log(arr2);
console.log(copyOfArr2);

return copyOfArr2;


} 

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

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

Challenge: Slice and Splice

Link to the challenge:

Splice deletes or replaces (inserting) a value or values.

So splice(1, 0, arr1) says “at index 1, delete 0 values and insert one value (an array, arr1)”.

splice(1, 0, ...arr1) says “at index 1, delete 0 values and insert all the values from arr1 at that point”.

Edit: Note it’s the values from the array, not the array itself. So if arr1 is [10,20,30], them splice(1, 0, ...arr1) is the same as writing splice(1, 0, 10, 20, 30)

slice is completely different thing, it says “create a copy (a slice) of part of an array from the first index given to the last”. It just has a very similar name, so tends to cause a bit of confusion.

1 Like

This is fantastic. Thank you so much for the explanation. One follow-up question, if I may, why can’t i create a new variable when using splice?

1 Like

Ah, so you can, but splice returns an array of the values you deleted. So in this case, that’s none, so it’s an empty array. splice (like push, pop, shift, unshift and sort) mutates the original array, and like them the value it returns isn’t the original array.

slice on the other hand doesn’t mutate, it creates a new array. So that first line, with arr2.slice() works because the return value of that is a slice of arr2 from index 0 until the the end of the array (that’s the default if you don’t pass any arguments to it).

1 Like

thank you so very much. It makes sense now, as when I was returning the var that had the splice method, it would return an empty array. THis makes perfect sense now. Thanks much!!!

1 Like

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