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
That's an interesting question! Let's pull up the pros (✔️) and cons (❌) for each alternative:
[].slice
[.slice is a typo.slice) faster.Contrary to what you'd think and read pretty much everywhere, [].slice.call(...) does NOT instantiate a new, empty Array just to access its slice property!.
Nowadays (it has been so for 5+ years – as of late 2018), the JIT compilation (1) is included everywhere you run JavaScript (unless you're still browsing the Web with IE8 or lower).
This mechanism allows the JS Engine to: (2)
... resolve
[].slicedirectly, and statically, as directArray.prototypereference in one shot, and just one configurable property access:forEach
Array.prototype.slice
Array.prorotype.slice) look fine until you try and run the code.❌: Runs slower
Array.prototype.slice is: (2)
... a lookup for the whole scope for an
Arrayreference until all scopes are walked 'till the global one ... because you can name a variableArrayany time you want.Once the global scope is reached, and the native found, the engine accesses its proottype and after that its method
...
O(N) scope resolution + 2 properties access (.prototypeand.forEach).
✔️: Allows you to seamlessly adapt to whichever coding conventions would strictly prevent you from having a line start with either (, [ or `
Definitely a good thing.
[].slice is better in pretty much every wayThey 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 usedvar slice = [].slice; - If you're concerned about the existence of Array, or if you just like the shorter syntax.