Why this code does not work

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function frankenSplice(arr1, arr2, n) {
let arr = [...arr2];
return arr.splice(n,0,...arr1);


}

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

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

Challenge: Slice and Splice

Link to the challenge:

1 Like

The problem with your solution is that you’re returning the method. Every method is a function, It returns a value. Splice formats your array and return a value.

If you have
let ar = [1, 2];
and you run console.log(ar.splice(0, 1))
The method will return [1] and It’ll be shown in the console. So your function just return an empty array.

Anyway, you can fix It by adjusting like this:

function frankenSplice(arr1, arr2, n) {

let arr = […arr2];

arr.splice(n,0,…arr1);

return arr;

}

Try to understand what’s going on, because this concept is important.

I think I understand what you are saying. We will modify the array internally when we call a splice on it, but the method array.splice() actually returns a new empty array by default. So in the code above, I am returning an empty array. Am I correct? and thank you for explaining that to me.

1 Like

If you want to know what the function is returning you can always wrap the call in a console.log.

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

I would suggest keeping MDN handy and reading about the methods you use.

MDN: Array.prototype.splice()

Return value

An array containing the deleted elements.

If only one element is removed, an array of one element is returned.

If no elements are removed, an empty array is returned.

1 Like

Oh I get it. Thank you!

1 Like

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