javascript-tips-and-tidbits icon indicating copy to clipboard operation
javascript-tips-and-tidbits copied to clipboard

The array in querySelectorAll example is not necessary

Open tontonsb opened this issue 5 years ago • 1 comments

It's not needed to convert to array in this example: [...$$("a[href *='#']")].forEach(console.log);

querySelectorAll returns NodeList. While that is not an array, it does have forEach natively. It would be more appropriate to use one of these:

  • $$("a[href *='#']").forEach(console.log)
  • [...$$("a[href *='#']")].map(element => console.log(element.href))

Maybe these things could be pointed out separately - what's NodeList, converting spreadables to arrays and also applying array methods to spreadable items directly. You know - [...$$('a')].map(myFun) creates an array while Array.prototype.map.call($$('a'), myFun) uses the map method on whatever.

[...$$("a[href *='#']")].forEach(console.log)

tontonsb avatar Jun 29 '19 21:06 tontonsb

Good point above; just wanted to point out a possible pitfall that some developers may need to be aware of.

It should be noted that IE11 does not support the forEach() method of the NodeList interface. So if one seeks to use the forEach() method on a NodeList while retaining support for IE11, it is necessary to convert the NodeList to an array.

If IE11 support is a concern, it should also be noted that IE11 does not support the spread syntax. So the following example will not work in IE11 without an appropriate polyfill: [...$$('span')].forEach(console.log);. If (for whatever reason) a polyfill is not being used, then we would need to convert the NodeList as follows: Array.from($$('span')).forEach(console.log);.

bronsonavila avatar Jan 18 '20 18:01 bronsonavila