Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does array slice convert javascript arguments to array

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?

like image 927
Jeff Storey Avatar asked Jan 14 '13 21:01

Jeff Storey


People also ask

Does slice change the array?

slice does not modify the original array. It just returns a new array of elements which is a subset of the original array.

Does slice mutate array JavaScript?

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.

Can you slice arguments JavaScript?

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) .

What is the purpose of the array slice method in JavaScript?

JavaScript Array slice() The slice() method returns a shallow copy of a portion of an array into a new array object.


2 Answers

From the EcmaScript specification on Array.prototype.slice:

NOTE The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice 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.

like image 169
Bergi Avatar answered Nov 03 '22 01:11

Bergi


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).

like image 26
Christophe Avatar answered Nov 03 '22 01:11

Christophe