Menü schliessen
Created: September 5th 2024
Last updated: November 29th 2024
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to Convert Iterables to Arrays

Tags:  guide,  Javascript

In JavaScript, you sometimes receive iterable objects such as Iterators (for example, through Map.prototype.keys()) or NodeList (for example, through document.querySelectorAll()) that aren't arrays. While these have their benefits and reasons to exist within JavaScript, often you'd rather just have an array (perhaps for the convenient helper methods).


The Solution(S)

The currently best supported and most widely applicable solution is using Array.from() like this:

Array.from(iterable)

A new and more convenient solution, which unfortunately isn't baseline available yet, is the chainable toArray() method. It lives on Iterator instances and can be used like so:

iterator.toArray()