Search code examples
javascriptarraysfunctional-programmingprototyperamda.js

When to use call or what is the benefit to use call in Javscript?


I am going through the source code of Ramda.JS which is a functional library for Javascript developers. These a few lines of codes confused me a bit.

var sort = _curry2(function sort(comparator, list) {
  return Array.prototype.slice.call(list, 0).sort(comparator);
});

My question is that

  • Array.prototype.slice.call(list, 0) should be exactly same to list.slice(0), but the second way is much shorter
  • Why use .call here, why not use the second way?
    • Is there any benefits to use call here?

References


an update

A great thanks to @VLAZ.

this screenshot is from what he suggested in his/her comment.

a.slice(0) and Array.prototype.slice.call(a, 0) are very different on non-array object.


Solution

  • It's worth noting that using Array.prototype.slice.call(arr, 0) over arr.slice() doesn't throw an error when arr isn't an array/string and arr doesn't have the slice method.

    Perhaps they wanted a more robust implementation, thus using the first approach.