[].slice or Array.prototype.slice

I’v come across both ways to apply Array prototypes to a native object:

arr = Array.prototype.slice.call(obj);
arr = [].slice.call(obj);

In similar fashion, getting the true type of a native array-like object:

type = Object.prototype.toString.call(obj);
type = {}.toString.call(obj);

A simple test:

function fn() {
    console.log(
        Array.prototype.slice.call(arguments),
        [].slice.call(arguments),
        Object.prototype.toString.call(arguments), 
        {}.toString.call(arguments)
    );
}

fn(0,1);

Fiddle: http://jsfiddle.net/PhdmN/

They seem identical to me; the first syntax is used more often, but the second is definitely shorter. Are there any shortcomings when using the shorter syntax?

Answer

They are identical regarding functionality.

However, the Array object can be overwritten, causing the first method to fail.

//Example:
Array = {};
console.log(typeof Array.prototype.slice); // "undefined"
console.log(typeof [].slice);    // "function"

The literal method creates a new instance of Array (opposed to Array.prototype. method). Benchmark of both methods: http://jsperf.com/bbarr-new-array-vs-literal/3

When you’re going to use the method many times, the best practice is to cache the method:

  • var slice = Array.prototype.slice; //Commonly used
  • var slice = [].slice; – If you’re concerned about the existence of Array, or if you just like the shorter syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *