Reputation: 81432
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?
Upvotes: 3
Views: 127
Reputation: 344685
Personally, I don't see a major problem with using your shortened syntax. Any performance impact would be minimal (and some engines will optimise accordingly anyway) so it boils down to a personal preference. There are a couple of alternatives available to you, though. For example, you could use the ECMAScript 5th edition Function.prototype.bind
to shorten it to anything you want:
var sl = Function.prototype.call.bind(Array.prototype.slice);
var myArr = sl([1, 2, 3], 1);
//-> [ 2, 3 ]
And of course, bind
can be implemented in unsupporting browsers.
In supported browsers/environments, you might also be able to use Array.from
or the spread operator for achieving the same results:
// Array.from works with any iterable or array-like object
var myArr = Array.from(arrayLike);
// Spread operator works only with iterables:
var myArr = [ ...arrayLike ];
If you're using a transpiler such as Traceur or Babel, these are already supported.
Upvotes: 1
Reputation: 27245
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(...);
Upvotes: 3