Return a Sorted Array Without Changing the Original Array - Why?

This is more of a ‘best practice’ question.

We’re taught to copy arrays using .slice(0) on FCC in the Functional Programming section. In this challenge we’re asked to copy the array by concatenating to an empty array. Upon testing, I’ve discovered that
[].concat(arr);
and
arr.concat([]);
are both valid and return the same result–which makes perfect sense.

My question is when and why we may choose one method over the other, between .slice(0) and [].concat()?

2 Likes

This will definitely help you…


scroll through the post and I guess you will get an accepable analysis…
Hope this helps :slight_smile:

2 Likes

That’s interesting…makes me wonder why we don’t explicitly learn [].concat() in the first place. It made perfect sense how to do it when asked, but it had not been shown previously in FCC challenges that I’m aware of.

Looks like I’ll be concatenating from now when I need to copy arrays. Thanks for the link, @phoenixabhishek!

2 Likes