Javascript: [Arrays] To convert an array-like object to an array, use Array.from

Created on 19 Sep 2016  路  7Comments  路  Source: airbnb/javascript

In 4.3 you say to use the array operator to copy arrays.

Why not do the same for creating arrays 4.4?

const foo = document.querySelectorAll('.foo');
const nodes = [ ...foo ];

Obviously the title would need to change, but I think the syntax is more consistent with 4.3.

editorial pull request wanted

Most helpful comment

A wise man once told me that the last thing we should care about is performance.

All 7 comments

That's a good point - we should be recommending the spread operator here, even though they're equivalent.

It might also be worth noting that it could be helpful to avoid the array creation step in some cases, ie:

// bad
const bar = [...foo].map(mapper);

// good
const bar = Array.prototype.map.call(foo, mapper);

Why would the array creation be a problem? IMO Array.prototype.map.call(foo) is harder to reason about than [...foo].

I agree with you a little bit - but the efficiency of avoiding the extra array reification matters. It's why Array.from takes a callback - and now that I think of it, that's why Array.from(foo, mapper) is actually loads better than [...foo].map(mapper).

A wise man once told me that the last thing we should care about is performance.

I might be wrong on this but I just did a speed test on both and the spread test keeps coming on top.

const arr = [ ...Array(100000).keys() ];
let test = function (i) { return i + 1; };

let arrFrom = function () {
  console.time('arrayFromTest');
  Array.from(arr, test);
  console.timeEnd('arrayFromTest');
};

let arrSpread = function () {
  console.time('arraySpreadTest');
  [...arr].map(test);
  console.timeEnd('arraySpreadTest');
};

arrFrom();
arrSpread();

What am I doing wrong?

results:
image

@rileybracken "running a microbenchmark". Performance can't be usefully measured in that way, since the engine will optimize the mapper function. Try using eval in the function, for example, to ensure it's never optimized.

Ah, now results are all over, I think I will just have to believe you :wink:.

Here it is if you want to try it. http://jsbin.com/garayo/1/edit?js,console

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brendanvinson picture brendanvinson  路  4Comments

progre picture progre  路  3Comments

xgqfrms-GitHub picture xgqfrms-GitHub  路  3Comments

graingert picture graingert  路  3Comments

mismith picture mismith  路  3Comments