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?

share|improve this question

77% accept rate
hrm. yeah. Why wouldn't the conversion be a feature of the arguments object, instead of slice? – Michael Paulukonis yesterday
feedback

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
feedback

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

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.