7

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?

2
  • 1
    hrm. yeah. Why wouldn't the conversion be a feature of the arguments object, instead of slice? Commented Jan 14, 2013 at 21:52
  • possible duplicate of how does Array.prototype.slice.call() work? Commented Jun 29, 2015 at 3:17

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.