Slice and Splice?

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

I don’t understand why this code doesn’t work?

  **Your code so far**

function frankenSplice(arr1, arr2, n) {

let second = arr2.slice();

let result = second.splice(n, 0, ...arr1);
return result;

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/92.0.4515.159 Safari/537.36

Challenge: Slice and Splice

Link to the challenge:

It’s failing because it isn’t working.

What is result? Log it out.

You have and erroneous assumption about splice. And anytime I’m unsure about prototype methods (which is often), I consult the docs, like here.

Does that help?

If I don’t indicate the ‘result’ variable and just simply apply ‘splice()’ on my first variable, everything works. So I just can’t grasp my head around as to why adding another variable - which I know is superfluous - does not give me the same result.

Don’t knock superfluous variables. Some of my best friends are superfluous variables.

But seriously, sometimes you add an extra variable because it makes it easier to read - that is completely legitimate. I don’t think it’s necessary here, but I also wouldn’t complain about it.

The issue is that you are misunderstanding how splice works. Some methods alter the original. Some keep original unchanged and return the data you want. If it changes the original, it probably returns something else. I can never remember so I always go to the MDN docs.

Read the link I gave you. At the top:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

And then the section for return value:

Return value

An array containing the deleted elements. …

Are you deleting any elements? Even if you were, is that what you want result to be?

1 Like

Okay, gotcha! Thanks! :slight_smile:

Googling things and reading docs are two of the most important tools a developer has. Seriously.

1 Like

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