There are these two ES6-methods of creating an array from an array-like or iterable object:
- Array.from():
let arr = Array.from(Object); - 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?
Array.fromis likely to give you more compatibility with older browsers. What I mean by this, takequerySelectorAll, it's an array like collection. WhenSymbol.iterator()was introduced it was likely implemented straight away for this, but what aboutElement.classListit returns aDOMTokenList, but some browsers vendors might not have implemented the iterator for it straight away. Saying all this it's likely that most class A browsers now have iterators implemented for everything that it makes sense for. But if you plan running on older browser it might be wise to check.