javascriptarraysforeachprototypenodelist

Loop through NodeList: Array.prototype.forEach.call() vs Array.from().forEach


So I want an easy way to loop through nodelists, and I always hated that I can't use forEach on nodeLists.

So, now I do: Array.prototype.forEach.call(nodeList, callback).

and for index, i do: Array.prototype.indexOf.call(nodeList, node).

and for pretty much everything I use Array.prototype on nodeLists.

But I'm wondering if these are considered hacks?

Are they the right way to do it?

Also, assuming I don't actually need an array from nodeList, is there an advantage of using Array.from(nodeList).forEach(callback) instead?


Solution

  • Array.prototype.forEach.call(nodeList, callback) will apply the logic of forEach on the node list. forEach just have a for loop in it that goes from index 0 to this.length and calling a callback on each of the items. This method is calling forEach passing the node list as its this value, since node lists have similar properties of an array (length and 0, 1, ...), everything works fine.

    Array.from(nodeList).forEach(callback) will create a new array from the node list, then use forEach on that new array. This second method could be split into two self explanatory lines:

    var newArray = Array.from(nodeList);  // create a new array out of the node list
    newArray.forEach(callback);           // call forEach on the new array
    

    The first approach is better because it doesn't create additional uneeded resources and it work on node lists directly.