Return directly or return a copy, result difference?

Return directly or return a copy, result difference?
0

#1

Tell us what’s happening:

Hi All, I have a question. I dont understand why this is two snippets are giving different results. If someone knows, I would appreciate someone could explain it to me.
I realise the second version creates a copy, I just don’t get why the result is different?

function slasher(arr, howMany) 
 {
   return arr.slice(howMany);
 }
// result is [3]
function slasher(arr, howMany) 
 {
   arr.slice(howMany);
   return arr;
 }
// result is [ 1, 2, 3 ]

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5.

Link to the challenge:


#2

This is because arr.slice() is returning a new copy that is sliced off from the beginning of the arr array.
In the first code, you are returning the array that is sliced from the arr array. And in the second example, you are returning the original arr array.

More documentation on this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Does that make sense?


#3

Hi @priidikvaikla,

You are right now, I see whats happening. Its too early here, my coffee has not kicked in yet :).

Thanks for the super quick reply!

D.