does rest params allocate array
function foo(a, b, ...rest) {
/*...*/
}
in example above its obvoius that array created, but what about this case
function foo(...rest) {
/*...*/
}
there rest
technicly the same as arguments
function foo() {
console.log.apply(null, arguments)
}
so, if i want avoid generate garbage could i prefer to use arguments
or not ?
also, does arguments
exists always or only when keyword used in function scope?
(if always, i assume thet using it is probably better, if not, is there any difference betwin rest and arguments
?)
rest
technicly the same asarguments
Not really. Rest parameters create a proper array, while the arguments
object famously is not an array but needs to be converted to one. And in sloppy mode, it behaves even weirder, aliasing the variables that are declared as parameters.
Does
arguments
exists always or only when keyword used in function scope?
It is created only when any code in the function refers to it - this is a relatively trivial optimisation with big impact, not having to allocate a new object for every single function call. And in fact, this optimisation goes even further in V8, sometimes not even instantiating the object even code refers to it, see What's the deal with optimising arguments? and Crankshaft vs arguments object by Vyacheslav Egorov for details.
Is there any difference, should i prefer to use
arguments
?
In modern code, you should generally prefer rest parameters. They are cleaner (less weird behavior), more declarative (easier to understand), and are actual arrays (so that you can use the usual array methods). They are the idiomatic choice.