Reputation: 1483
What's the difference between
function(...args) {
// args is an array
}
and
function() {
// arguments is an array-like
}
Since it's pretty easy to convert an array-like to array, is there any other differences?
A similar question:
myFunction.apply(null, args);
and
myFunction(...args);
Upvotes: 1
Views: 1141
Reputation: 4738
There are four main differences between rest parameters and the arguments object:
- The
arguments
object is not a real array, while rest parameters areArray
instances, meaning methods likesort()
,map()
,forEach()
orpop()
can be applied on it directly.- The
arguments
object has the additional (deprecated)callee
property.- In a non-strict function with simple parameters, the
arguments
object syncs its indices with the values of parameters. The rest parameter array never updates its value when the named parameters are re-assigned.- The rest parameter bundles all the extra parameters into a single array, but does not contain any named argument defined before the
...restParam
. Thearguments
object contains all of the parameters — including the parameters in the...restParam
array — bundled into one array-like object.
Upvotes: 0
Reputation: 26797
Re: differences between apply()
and spread (when passing null
or such as the thisArg
to apply()
as in the example):
myFunction.apply(null, args);
myFunction(...args);
Aside from spread being newish, so not as widely supported currently, apply()
accepts an array or array-like object of arguments, whereas spread will work on any iterable. For example, you could spread a Set
or Map
as the arguments while you couldn't pass it as the argArray
argument to apply()
(though you could of course spread it as the arguments to call()
: myFunction.call(whatever, ...someIterable)
).
Since it's pretty easy to convert an array-like to array, is there any other differences?
It's not really that easy for arguments
. Doing it wrong (or perhaps at all) can cause the JS engine to deoptimize the function, and if there is a right way to do it that avoids that it requires annoying boilerplate to do it.
Upvotes: 2
Reputation: 198324
...args
is new; was not available till ES6function(foo, bar, ...others)
Array.prototype.slice.call(arguments, 0)
...args
is more obvious to code readersHowever, as a corollary to 1, not everything supports it yet.
Upvotes: 6