'What is the difference between Array.from(Object) and [...Object]? [duplicate]

There are these two ES6-methods of creating an array from an array-like or iterable object:

  1. Array.from(): let arr = Array.from(Object);
  2. Spread syntax: let arr = [...Object];

Here are both in action doing exactly the same:

let string = 'foobar';

console.log( [...string] );
console.log( Array.from(string) );

What is the difference between the two and which one should I use preferably to convert a HTMLCollection to an array?



Solution 1:[1]

Update for 2022

Most of us don't have to support IE anymore, and it matters a lot less which one you use than it used to because there's less potential for the kind of bug I describe below to slip through to production.

Original answer

There isn't much difference in terms of what each does (except in a few contrived scenarios), but you should almost certainly use the spread syntax. The reason is that syntax will automatically be converted by babel, the Typescript compiler, etc. but you'll need to add a polyfill for Array.from unless you just don't care about older browsers. In general prefer compile/build-time solutions to run-time solutions.

Solution 2:[2]

Spread syntax only works with objects that implement the iterator method (Symbol.iterator()).

Array.from() on the other hand will also work on array-like objects(indexed elements) which do not implement the iterable method.

Array.from() can be used for HTML collections because of the readability as the results for both will be same in this case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ellipsis