The first method is ES5 compatible:
Array.prototype.forEach.call(nodeList, callback).
The second method uses Array.from
which was only defined in ES6:
Array.from(nodeList).forEach(callback)
However, you are not optimising the use of Array.from
here, because you first create the whole array, and then iterate over it with forEach
.
Instead use the second argument of Array.from
:
Array.from(nodeList, callback)
Now the whole operation happens in one iteration.
The nice thing is that in the above expression, the callback is used as a mapping function, so if it returns a value, the whole expression returns the array as defined by those return values. But using this is of course optional. For instance, you could create an array with the text contents of the nodes like this:
texts = Array.from(nodeList, node => node.textContent)
Warning
If you use Array.from
with callback, and the node list is a live node list (see NodeList), and you mutate the node list in the callback, then this can have undesired effects. In that case use the two step method where you first turn the node list into an array, and only then perform the callback on its entries.