Fastest Way to Convert JavaScript NodeList to Array?
Convert a NodeList to an Array instantly with the spread operator ...
:
The need for speed: Classic for loop
Consider this if you've got a mighty big NodeList and performance is a priority. It might not look as slick as Array.from()
, but it sure does hustle:
Storing your NodeList's length in a variable or declaring your array length pre-loop could speed things up further. Fast and furious!
Utilizing ES6: Array.from()
This performs a similar feat but in a more suave fashion:
ES6 support is required, though. So keep an eye out for compatibility issues.
Spread it out: Spread operator
If your NodeList isn't a giant and you prefer keeping your code crisp and short, the spread operator ...
might be your cup of tea:
Just like Array.from()
, it's only for the modern browsers who enjoy the ES6 afternoon tea.
Pushing or accessing?
Here's another fun twist. Directly assigning array indices can sometimes outperform the good old push
:
Avoid unnecessary conversions
Ask yourself: do you really need to convert your NodeList to an Array? The nodeList.forEach() method can also iterate over NodeList elements with zero conversion:
Instrumental performance tests
Tools like jsPerf can help you figure out which method bops to the top in terms of performance in your particular scenario - be it Array.from()
, the spread operator, or a for loop.
Fear no browsers!
In a world where some users are still on IE11 (scary, right?), you may need to use polyfills for techniques such as Array.from()
and ensure that your ES6 tricks still work.
Avoiding outdated methods
Just like parachute pants and fanny packs, Array.prototype.slice.call()
isn't cool anymore. Modern techniques perform better.
Browser compatibility: Are you in or out?
Not every browser is elite enough to handle all the latest and greatest ES6 features. Make sure to dust off those old transpilers and polyfills.
Selecting the best tool for your scenario
Choose wisely: readability, compatibility, and performance are all factors to consider when choosing your array conversion strategy.
Was this article helpful?