I came across the following code:
var f = function () {
var args = Array.prototype.slice.call(arguments).splice(1);
// some more code
};
var args = Array.prototype.slice.call(arguments).splice(1);
First takes a copy of arguments
(*), then removes all but the first item from it (in a non-standard way), and assigns those items being removed to args
.
The extra array being produced, then altered and thrown away is quite redundant. It would be better to say — as the version in the answer you linked to indeed does:
var args = Array.prototype.slice.call(arguments, 1);
Partial function application is also a feature of the function.bind
method, being standardised by ECMAScript Fifth Edition. Until browsers have implemented it, you can pick up an a fallback JS-native version from the bottom of this answer.
*: array.slice()
is the normal idiom for copying an array, and array.slice(1)
for taking the tail. It has it be called explicitly through the Array.prototype
because arguments
is not an Array, even though it looks just like one, so doesn't have the normal array methods. This is another of JavaScript's weird mistakes.
You quite often see people using the Array.prototype
methods on objects that aren't Arrays; the ECMAScript Third Edition standard goes out of its way to say this is OK to do for the arguments
array-like, but not that you may also do it on other array-likes that may be host objects, such as NodeList or HTMLCollection. Although you might get away with calling Array.prototype
methods on a non-Array in many browsers today, the only place it is actually safe to do so is on arguments
.