To reach into the arguments of a function, I explained here that you should write:
1function () {
2 const args = new Array (arguments.length);
3 for (var i = 0; i < args.length; ++i) {
4 args[i] = arguments[i];
5 }
6 // do whatever you want with the args array
7}
Arguments belong to the past
As Kyle Simpson explains in his book You Don’t Know JS: ES6 & Beyond, ES2015 comes with a feature called rest parameters, which uses the same ...
syntax as spreads.
1function(...args) {
2 // do whatever you want with the args array
3}
This is the preferred way of reaching into a function’s arguments
. So
rather than resorting to the optimization presented in this post, simply use the
rest parameters.
Rest parameters or arguments
?
There are a few differences, though:
-
Rest parameters only contain the remaining parameters whereas
arguments
contains all parameters. The difference would be visible infunction foo(a, b, ...args)
wherea
andb
would not show up inargs
, but would be present inarguments
. -
The rest parameters are a real
Array
, whereasarguments
is not. -
The rest parameters does not have additional properties, whereas the
arguments
object contains propertiescallee
andlength
, and in some cases alsocaller
(which has been deprecated).
What is Babel doing?
The current version of Babel (6.2.1) transpiles this ES2015 code:
1function join (...args) {
2 console.log (args);
3}
to this plain ES5 source:
1function join() {
2 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
3 args[_key] = arguments[_key];
4 }
5 console.log (args);
6}
There is no surprise in this code. It is about the same as I would have done manually.