4

Why would you slice an array like this:

Array.prototype.slice.call(arr, 3);

Instead of simply:

arr.slice(3);

?

What are the benefits of using the prototype and the call?

Thanks!

1
  • 1
    'arr' may not be an actual array. It could be a NodeList, or an arguments parameter, therefore the slice method isn't available. Commented Aug 10, 2013 at 20:15

1 Answer 1

6

The key benefits are realized when "arr" is not an array, but something like an array; specifically, something with a "length" property and numerically-keyed properties. Good examples are the arguments object and NodeList objects from a DOM. Those things won't have a "slice" method, but they do have numerically-keyed properties and a "length" property.

The trick works because the "slice" method is pretty forgiving.

If you see it being used with something that's definitely an array already, then you're looking at code written by a confused person :)

Oh, and note also that a short-cut is:

var foo = [].slice.call(arguments, 0);

You don't have to go to the prototype directly if you don't want to; you can get at it from an array instance just as easily. (Yes, it costs a dummy allocation, but in this day and age I wouldn't be surprised if VMs optimized that away.)

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

3 Comments

LOL. Thanks! That helps. So, to make sure I understand: Using the prototype/call method allows you to use prototype methods of objects on other objects that aren't of the given type?
@MrA yes - but: it only works if it works. In other words, that trick lets you get at a method and invoke it such that this is some object you've chosen. Will the method work? Well, maybe, or maybe not. In this case, it does.
The methods that work on any object are documented in the specification as generic methods. You can directly copy a reference to them to avoid creating your own implementation. E.g. List.prototype.add = Array.prototype.push. or NodeList.prototype.each = Array.prototype.forEach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.