Why does applying the slice method to the javascript arguments
value as follows Array.prototype.slice.call(arguments)
convert it to an array? If slice is used on arrays, and arguments
is not an array, then how does this work? Is it just a special case when slice
is applied to arguments?
slice does not modify the original array. It just returns a new array of elements which is a subset of the original array.
slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows: For objects, slice copies object references into the new array.
All you know that arguments is a special object that holds all the arguments passed to the function. And as long as it is not an array - you cannot use something like arguments. slice(1) .
JavaScript Array slice() The slice() method returns a shallow copy of a portion of an array into a new array object.
From the EcmaScript specification on Array.prototype.slice
:
NOTE The
slice
function is intentionally generic; it does not require that itsthis
value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether theslice
function can be applied successfully to a host object is implementation-dependent.
And so, slice
works on every object that has a length
property (like Arguments
objects). And even for those that do not, it then just returns an empty array.
Right, this is a trick that takes advantage of the fact that arguments are an enumerable list. It works on other enumerable lists too (for example nodelists).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With