Rest Arguments in ES5
Heads Up!
This one is from 2016 and is pretty much obsolete now. Rest parameters have been supported in every major browser for years (and Internet Explorer is officially gone), so you can just use
...args. If you’re stuck working withargumentsfor some reason,Array.from(arguments)is a cleaner way to turn it into an array. Also keep in mind that arrow functions don’t get their ownargumentsobject at all.
The ES2015 specification introduces support for rest parameters (sometimes called variadic arguments, not to be confused with spread syntax, which does the opposite). Sadly, not everyone is currently able to use ES2015+ syntax and features, typically due to browser support constraints. Here’s a solution for those of you stuck using ES5.
#The Code
Let’s look at an example of what we’d like to implement using ES2015.
function example (foo, ...bar) {
/* ... */
}
And here is an equivalent operation in ES5.
function rest (args, start) {
return Array.prototype.slice.call(args, start || 0);
}
function example (foo) {
var bar = rest(arguments, 1); // array of all arguments after "foo"
/* ... */
}
#Why It Works
Javascript functions automatically receive all of their arguments in an array-like object called arguments. Though arguments has a length and indexed values, it’s not an actual array, meaning you miss out on array methods like .map() and .forEach().
To convert arguments to an array, we can coerce it by setting it as the context for Array.prototype.slice() by using .call(). This works because .slice() only needs its context to be array-like (have a length and indexed values), rather than an actual array.
The first argument of .call() is the desired context of the function we’re calling. The subsequent arguments are 1-to-1 with how we’d typically invoke the function. This means that the next argument we want is the index we wish to start slicing from.
0 would result in slicing from the beginning of the array, resulting in all arguments being presented in the returned array. 1 would skip the first argument, and so on.