views:

63

answers:

2

I found that a neat way to convert an array-like object (e.g. NodeList, Arguments) into a real array is to use:

Array.prototype.slice.call(...);

Then, I thought of a way to shorten this syntax:

[].slice.call(...);

Would the latter method waste time and/or memory by creating a new array each time that it is called? Should I avoid this syntax in complexity-essential applications, or do JavaScript engines optimise this out?

+3  A: 

I would think the [] notation probably should be avoided. If you want to save space, why not just do:

// Once in JS
var slice = Array.prototype.slice.call;

// Many places in JS
slice(...);
Tauren
There's a slight quirk about your solution; doing this makes `slice` return `window` because of some sort of contextual error. It might work better to do something like `function slice(a) { return Array.prototype.slice.call(a); }`
Delan Azabani
Really? Perhaps your right, I didn't test it. I was mainly just trying to get my point across.
Tauren
+1  A: 

Personally, I don't see a major problem with using your shortened syntax. Any performance impact would be minimal so it boils down to a personal preference. FWIW, you could use the ECMAScript 5th edition Function.prototype.bind to shorten it to anything you want:

var sl = Array.prototype.slice.call.bind(Array.prototype.slice);
var myArr = sl([1, 2, 3], 1);
//-> [ 2, 3 ]

And of course, bind can be implemented in unsupporting browsers.

Andy E
Great tip! I would upvote, but I've hit my vote limit for now.
Delan Azabani