Why doesn't my first solution work? Slice and Splice

Tell us what’s happening:
My first attempt at this challenge failed. With a small tweak to the code, I have a solution that passes. I’ve seen that often you can write something like return someVar.toUpperCase(); and it will return the variable in all caps. You don’t have to convert to upper case before returning the solution. In this challenge, it fails when I don’t splice before returning the solution and I don’t understand why. I may be overlooking the obvious, so I could use some help. Thanks!

Your code so far

// this passes the challenge
function frankenSplice(arr1, arr2, n) {
    let newArr = [...arr2];
    newArr.splice(n, 0, ...arr1);
    return newArr;
}
      
// this fails the challenge
function frankenSplice(arr1, arr2, n) {
    let newArr = [...arr2];
    return newArr.splice(n, 0, ...arr1);
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0.

Challenge: Slice and Splice

Link to the challenge:

HI @latechlogan !

Welcome to the forum!

If you console.log the two answers you will see why your first attempt didn’t work.

Correct

function frankenSplice(arr1, arr2, n) {
    let newArr = [...arr2];
    newArr.splice(n, 0, ...arr1);
    console.log(newArr) // [ 4, 1, 2, 3, 5, 6 ]
    return newArr; 
}


frankenSplice([1, 2, 3], [4, 5, 6], 1);

Incorrect

function frankenSplice(arr1, arr2, n) {
    let newArr = [...arr2];
    console.log(newArr.splice(n, 0, ...arr1)) //[]
    return newArr.splice(n, 0, ...arr1);
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

If you see unexpected behaviour, check what the method returns. .toUpperCase(), returns the new uppercase string, .slice() returns the part that you sliced out of the original array, but .splice() returns the deleted items from the array, not the new array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Ah, I see… I forgot that the return value can be different from the result of the method. Thanks for your help!

Thanks for your help! I did actually console.log my first solution and was seeing that the result was an empty array. I just couldn’t figure out why that was the result. In fact, I was changing the delete count to see if I could figure out what was going on and saw that deleting items actually filled the array. :man_shrugging: I didn’t quite connect the dots that I was getting the return value of splice instead of the result of the splice as jsdisco pointed out.

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