nas5w / javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
MIT License
1.2k stars 72 forks source link

The array in querySelectorAll example is not necessary #22

Open tontonsb opened 5 years ago

tontonsb commented 5 years ago

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:

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)

bronsonavila commented 4 years ago

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);.