Return Part of an Array Using the slice Method [Why?]

Tell us what’s happening:

Your code so far


function sliceArray(anim, beginSlice, endSlice) {
  // Add your code below this line
  return anim.slice(beginSlice, endSlice)
  
  // Add your code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method

My question is that since slice() won’t mutate the original array, why do we need a callback?
Can we just do inputAnim.slice()?

As in the parameters being put in for slice? Although the 1st and 2nd arguments for slice are optional, if both left to nothing with just calling slice, it’s just going to copy the entire array. You’re right in the sense that it doesn’t mutate the array, as it only makes a shallow copy of it.

The purpose of the parameters of slice is to indicate where in the array that you want, in a sense, to slice out from. With the first argument being the start on where you want to slice and the second, being where the slice will end(with the end index not included)

However as stated earlier those are optional, So if you only specify 1 argument for slice, the slice will start from that specified index onto the end of the array. But if both left empty it will just return a copy of that array.

Side note, if I totally misread your question I’m sorry lol too tired, and probably need to sleep.

1 Like

we are not using a callback here - a callback is the function you use as argument of an other function

if you mean why are we creating the sliceArray function when we could just use the slice method directly on the array, it is for testing purposes I think

1 Like

I was wondering why do we need to create a function for it.
Maybe it’s me didn’t explain my question well. lol
Thank you for your time. =)

Yes, that’s what I was wondering about.
I see!! Thank you!