Question about return on this problem

Tell us what’s happening:
Describe your issue in detail here.
I have a question about the placement of return in the algorithm.
I tried to return the code earlier (See below) in order to see if I could shorten the code.
The code didn’t pass the test.
My theory is that I am returning too early as the computer needs time to complete the splice() method. Trying to print it while in the process of completing it would return undefined.
Returning on the next line works because the computer has been able to place everything already. Am I correct or is there something else happening that I’m not understanding?

   **Your code so far**

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

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

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Challenge: Slice and Splice

Link to the challenge:

When you say if you put the return on the next line it passed do you mean

function frankenSplice(arr1, arr2, n) {
 let newArr = arr2.slice();

return newArr.splice(n, 0, ...arr1);

Like that? Because that fails for me as well when I run it

Lucky for us, that’s completly wrong ^^°

The problem is not the “return” but what comes after.
The working code returns newArr - an array, nothing special.

What does the failing code return? newArr.splice(n, 0, ...arr1)
So what’s that? It’s a function, as indicated by the brackets. So what is the value of a function? Well whatever is written after the return IN THAT FUNCTION.
Soooo what does splice() return? You suspect it returns the altered array. But because you didn’t console.log() the result, you don’t actually know. So that’s something to avoid in the future.

The .slice() function returned an array, as you assigned it’s value to newArr.
However you didn’t use an assignment on .splice() - meaning it just changes newArr inplace. So it automatically replaces the value newArr, it would be redundant to then also return the new value.

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