4 ms·
alternatively, if you need to use anything other than `forEach` for working on the list, you can turn the NodeList into an array using the array spread syntax (
by dhritzkiv 4y ago
alternatively, if you need to use anything other than `forEach` for working on the list, you can turn the NodeList into an array using the array spread syntax (equivalent to using Array.from) e.g.
[...document.querySelectorAll('a')]
.filter(node => node.getAttribute("data-foo") === "bar")
- megous 4y agoNot everyone wants to be so wasteful.
- dhritzkiv 4y agowhat do you mean by "wasteful"?
- megous 4y agoCreating an array, populating it with however many elements just to be able to call some methods and destroying it immediately afterwards. And doing it all over the app, just because it's syntactically convenient. (all while you already have an iterable collection in the form of NodeList)
- hombre_fatal 4y agoIt is a bit weird to consume an iterator into an array when a NodeList is already iterable. Not sure why it caught on.
- megous 4y agoI see it a lot with other iterables, too. People may like one liners and functional style more than a procedural `for (of)` construct, so they use `[...iterable].any_array_function(...)` everywhere, except when foced not to by async code :). Might also have something to do with Redux and immutable patterns. (the use of spread operator in general)
- mr_toad 4y agoUsually it’s because you want to use an array function like .filter() that isn’t implemented by the iterable itself.
- megous 4y agoNodeList.prototype.filter = Array.prototype.filter; and you can querySelectorAll('...').filter(el => ...) without any copies.
- deleted 4y ago[deleted]
- shirogane86x 4y agoI'm also one of those guys that will always spread NodeLists (and other iterable-but-not-array type of objects) but it's really only because I find functional style a lot more readable than imperative style for loops. It might be iterable, but if it doesn't have map/filter/reduce and friends, might as well not be for me.
- megous 4y agoNodeList.prototype.filter = Array.prototype.filter; and you can querySelectorAll('...').filter(el => ...) without any copies. ditto for other mentioned functions. Prototypal nature of Javascript is there for a reason.
- shirogane86x 4y agoIn every single project or company I've ever worked on/with, monkey patching was _extremely_ frowned upon (for good reasons). Also, how would you be able to filter without any copies? you'd at least be forced to make one. filter is _not_ supposed to mutate anything. so you'd have to create a new Array and/or NodeList, and put the filtered values back in. Even then, doing all this stuff for what is effectively one single copy that is likely to be insignificant at a performance level is, in my opinion, excessive. I just copy once and make the code clearer.